How to change the color of TextView at runtime with shape attribute on Android?

走远了吗. 提交于 2019-12-06 15:14:51

问题


I'm using shape attribute like this:

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle"
    android:padding="10dp">
<solid
    android:color="#FFFFFF" />
<corners
    android:bottomRightRadius="15dp"
    android:bottomLeftRadius="15dp"
    android:topLeftRadius="15dp"
    android:topRightRadius="15dp" />
</shape>

and

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/rounded_textview">
        </TextView>

If I change the color at runtime with the following method:

TextView.setBackgroundColor();

The shape I used is disappear. What should I do to change it with the proper way? Or should I must have to generate lots of shape for just different colors?

Thanks.


回答1:


I found a solution with PaintDrawable which contains color and radius attributes. But It have to set the color in the contructor. So I have to new a PaintDrawable at runtime every time and set it to the background drawable of a TextView.

public static PaintDrawable getRoundedColorDrawable(int color, float radius, int padding) {
    PaintDrawable paintDrawable = new PaintDrawable(color);
    paintDrawable.setCornerRadius(radius);
    paintDrawable.setPadding(padding, padding, padding, padding);
    return paintDrawable;
}



回答2:


You need to set the background a different shape with the correct Solid element. setBackgroundColor I believe just is a short cut to something like:

void setBackgroundColor(int color){
 ColorDrawable drawable = new ColorDrawable(color);
 setBackgroundDrawable(drawable);
}

So yea you will need a few shapes :)




回答3:


I had the same problem

You can use this method

TextView tv = // ... //;
tv.setBackgroundResource(R.drawable.myshape);

It works fine for me!



来源:https://stackoverflow.com/questions/4020503/how-to-change-the-color-of-textview-at-runtime-with-shape-attribute-on-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!