16

我必须在 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>
4

2 回答 2

57

你需要使用setBackgroundResource()方法。

例如 :

best_deals.setBackgroundResource(R.drawable.headerradius);

有关setBackgroundResource() 的更多信息。

于 2013-07-20T07:24:22.240 回答
2

有效的最终代码

比 JELLYBEAN 更旧的 API 有不同的方式来以编程方式加载可绘制对象。尝试这个:

       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));
        }
于 2016-10-28T06:57:02.253 回答