开发者

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

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:开发者_JAVA百科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.


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


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 :)


I had the same problem

You can use this method

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

It works fine for me!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜