Can anyone explain to me why this is happening?
I have a fairly simple class extending TextView. When I set the background colour to Color.BLUE, padding works fine. When I change the background resource to android.R.drawable.list_selector_background, my padding is no longer applied. What the F?
Here is my UI class:
public class GhostDropDownOption extends TextView {
TextView text_view;
public GhostDropDownOption(Context context, AttributeSet attrs) {
super(context, attrs);
setup(context);
}
public GhostDropDownOption(Context context) {
super(context);
setup(context);
}
private void setup(Context context) {
this.setClickable(false);
// THE 2 LINES BELOW ARE THE ONLY THING I'M CHANGING
//this.setBackgroundResource(android.R.drawable.list_selector_background);
this.setBackgroundColor(Color.BLUE);
}
}
And I'm using it in the layout like this:
<trioro.voyeur.ui.GhostDropDownOption
android:id="@+id/tv_dropdown_option_1"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:gravity="center_vertical"
android:text="@string/request_control_dropdown_option_1"
android:textColor="#000000"
android:padding="10dip"/>
And this is the result of changing the background:
You should set your background drawable in XML if at all possible. If you set it in code, it will use the padding from your drawable resources rather than what you set in XML, so if it's necessary to do it programmatically, you'll want to retrieve the current padding, store it temporarily, set the background, and then set the padding back as @TofferJ suggests.
The reason for this is that the drawables themselves can have padding, in the case of 9-patch images (where the bottom and right pixel borders define the amount of padding).
Your solution should be to just set your background resource in XML:
android:background="@android:drawable/list_selector_background"
although I believe that may be a private drawable resource that you'll have to copy into your project first.
The call to:
this.setBackgroundResource(android.R.drawable.list_selector_background);
will remove any previosly set padding (this is to make it work properly with 9-patch assets).
Try to set the padding in code after the line above, like this:
this.setPadding(PADDING_CONSTANT, PADDING_CONSTANT, PADDING_CONSTANT, PADDING_CONSTANT);
Just remember that the values sent to setPadding is in pixels NOT dip!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With