以编程方式从Android中的drawable创建textview背景

时间:2013-07-20 07:22:16

标签: android background gradient textview

我必须在Android TextView上以编程方式设置背景

我使用下面的代码。它不起作用,它也给了我nullpointerexception错误。

best_deals = (TextView) findViewById(R.id.bestdeals);
 best_deals.setBackground(getResources().getDrawable(
                                       R.drawable.headerradius));

但我必须把这些

best_deals.setTextColor(Color.parseColor("#be2351"));表示它正在运作

上面的代码有什么问题?

这是我的 header_redius.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" android:padding="10dp">
    <solid android:color="#000000"/>
     <corners 
      android:radius="15dp"
     />
     <gradient
            android:startColor="#434343"
             android:centerColor="#434343"
            android:endColor="#434343"
            android:angle="270" 
            android:type="linear"
            />
        <padding android:left="10dp"
     android:top="0dp"
     android:right="10dp"
     android:bottom="0dp"/> 
        <stroke
            android:width="2dp"
            android:color="#000000" />
            </shape>

2 个答案:

答案 0 :(得分:41)

您需要使用setBackgroundResource()方法。

例如:

best_deals.setBackgroundResource(R.drawable.headerradius);

有关setBackgroundResource().

的更多信息

答案 1 :(得分:0)

有效的最终代码

比JELLYBEAN更旧的API有不同的方式以编程方式加载drawable。试试这个:

       final int sdk = android.os.Build.VERSION.SDK_INT;
        if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
            textView.setBackgroundDrawable(getResources().getDrawable(R.drawable.shape_rect_outline));
        } else {
            textView.setBackground(getResources().getDrawable(R.drawable.shape_rect_outline));
        }
相关问题