在安卓中以编程方式从可绘制对象创建TextView背景

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>
2个回答

58

2
谢谢提供这么好的解决方案...我已经尝试了这些解决方案,但我的 ID 是错误的。这就是为什么我会得到空指针错误异常。现在我已经得到了输出。谢谢。 - user2218667

2

最终可用的代码

早期版本的API与JELLYBEAN不同,有不同的方式来在程序中加载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));
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接