【问题标题】:Programmatically create textview background from drawable in Android以编程方式从Android中的drawable创建textview背景
【发布时间】:2013-07-20 07:22: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>

【问题讨论】:

    标签: android background gradient textview


    【解决方案1】:

    您需要使用setBackgroundResource() 方法。

    例如:

    best_deals.setBackgroundResource(R.drawable.headerradius);
    

    更多关于setBackgroundResource().

    【讨论】:

    • 感谢您给我这么好的解决方案...我已经尝试过这些解决方案。但是我的 id 是错误的。这就是为什么我得到空指针错误异常。现在我得到了输出。谢谢。跨度>
    【解决方案2】:

    有效的最终代码

    比 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));
            }
    

    【讨论】:

      猜你喜欢
      • 2016-06-12
      • 2015-04-19
      • 1970-01-01
      • 2021-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-06
      相关资源
      最近更新 更多