填充不适用于某些后台资源

时间:2012-11-13 15:06:57

标签: android android-view

任何人都可以向我解释为什么会这样吗?

我有一个相当简单的类扩展TextView。当我将背景颜色设置为Color.BLUE时,填充工作正常。当我将后台资源更改为android.R.drawable.list_selector_background时,我的填充不再应用。什么F?

这是我的UI类:

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);
    }
}

我正在布局中使用它:

<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"/>

这是改变背景的结果: enter image description here

2 个答案:

答案 0 :(得分:14)

致电:

this.setBackgroundResource(android.R.drawable.list_selector_background);

将删除任何预先设置的填充(这是为了使其与9补丁资产一起正常工作)。

尝试在上面一行之后的代码中设置填充,如下所示:

this.setPadding(PADDING_CONSTANT, PADDING_CONSTANT, PADDING_CONSTANT, PADDING_CONSTANT);

请记住,发送到setPadding的值是以像素为单位不是dip!

答案 1 :(得分:2)

如果可能,您应该以XML格式设置背景。如果你在代码中设置它,它将使用你的可绘制资源的填充而不是你在XML中设置的填充,所以如果有必要以编程方式进行,你需要检索当前的填充,临时存储,设置背景,然后将填充设置为@TofferJ建议。

这样做的原因是,在9个补丁图像的情况下(其中底部和右侧像素边界定义了填充量),drawable本身可以具有填充。

您的解决方案应该是以XML格式设置后台资源:

android:background="@android:drawable/list_selector_background"

虽然我认为这可能是一个私人可绘制资源,您必须先将其复制到项目中。