2012-11-13 36 views
8

任何人都可以向我解释为什么会发生这种情况吗?填充不适用于某些背景资源

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

回答

11

致电:

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

将删除任何以前设置的填充(这是为了使它适用于9修补程序资产)。

尝试设置填充在代码行后上方,这样的:

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

只要记住,发送到setPadding值是以像素沾!

+1

更多信息可以在这里找到:http://stackoverflow.com/questions/2886140/does-changing-the-background-also-change-the-padding-of-a-linearlayout – TofferJ

2

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

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

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

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

虽然我相信可能是你必须复制到项目第一私人绘制资源。

+1

谢谢,这是一个伟大的解决方案,因为我只使用我的UI类的几个实例。原来我没有把它复制到我的项目中。该行将从安装应用程序的任何设备中获取内置的绘图。 – raydowe