views:

42

answers:

2

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.

A: 

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

Greg
Yes, but I'm seeking an alternative solution that don't have to set the shape again because I've to change to various colors. But It's going to be lots of xml files. Or if just set the background with a ColorDrawable as your code, the corner attribute is gone.
shiami
Maybe I can get the original drawable and just change its color. But I don't see there is a method like setColor().
shiami
You might be able to by grabbing the ShapeDrawable, grabbing the Paint, via getPaint() and setting the color of the Paint via setPaint().
Greg
Somehow, it returns a GradientDrawable. And can not get the Paint
shiami
If it returns a GradientDrawable, then you can call setColor on it.
Greg
A: 

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