Android/Java: how to set background color of MaterialShapeDrawable with int Color?

Viewed 658

I have a TextView with rounded corners.

Here is my code:

float radius = 10f;
ShapeAppearanceModel shapeAppearanceModel = new ShapeAppearanceModel()
   .toBuilder()
   .setAllCorners(CornerFamily.ROUNDED,radius)
   .build();
    
MaterialShapeDrawable shapeDrawable = new MaterialShapeDrawable(shapeAppearanceModel);
    
ViewCompat.setBackground(textView,shapeDrawable);

Now, I want to change programmatically the background color of the textView.

When I do :

shapeDrawable.setFillColor(ContextCompat.getColorStateList(this,R.color.design_default_color_background));

it works; the background color is changed.

Now, I want to change the background color with an int color like Color.RED or any random color defined with Color.RGB(r, g, b, a) or Color.RGB(r, g, b).

How can I do that? Should I use shapeDrawable.setFillColor or another method?

Thanks.

4 Answers

ANSWER to my question.

Here is the code I added in order to be able to set any background color :

 int[][] states = new int[][] {
                new int[] { android.R.attr.state_hovered}, // hovered
        };

 int[] colors = new int[] {color};
 ColorStateList myColorList = new ColorStateList(states, colors);
 shapeDrawable.setFillColor(myColorList);
 shapeDrawable.setState(states[0]);

Crazy to have to write so much code just to change a background color...

Thanks all for your help !

You can define global value for your color just like this

 public static final int RED = 0xffff0000;

And use like this.

 shapeDrawable.setFillColor(ContextCompat....(this, RED));

The method setFillColor works with a ColorStateList.
You can use something like:

int[][] states = new int[][] {
    new int[] { android.R.attr.state_focused}, // focused
    new int[] { android.R.attr.state_hovered}, // hovered
    new int[] { android.R.attr.state_enabled}, // enabled
    new int[] { }  // 
};

int[] colors = new int[] {
    Color.BLACK,
    Color.RED,
    Color....,
    Color....
};

ColorStateList myColorList = new ColorStateList(states, colors);

simply use setTint method in your MaterialShapeDrawable like this:

val shape = MaterialShapeDrawable(shape)
shape.setTint(resources.getColor(R.color.colorPrimary, null))
Related