10

谁能向我解释为什么会这样?

我有一个相当简单的类扩展 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"/>

这是改变背景的结果: 在此处输入图像描述

4

2 回答 2

15

呼吁:

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

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

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

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

请记住,发送到 setPadding 的值是像素而不是下降!

于 2012-11-13T15:14:40.967 回答
3

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

原因是可绘制对象本身可以有填充,在 9-patch 图像的情况下(底部和右侧像素边界定义填充量)。

您的解决方案应该是在 XML 中设置您的背景资源:

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

尽管我相信这可能是一个私有的可绘制资源,您必须首先将其复制到您的项目中。

于 2012-11-13T15:20:56.333 回答