1

I am trying to set the color of my shape programmatically, inside my drawable I created a rounded shape (rounded_button.xml):

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

And now I want to change it color in my activity.

public void setShapeColor() {
    Drawable shapeDrawable = ResourcesCompat.getDrawable(getResources(), R.drawable.rounded_button, null);
    shapeDrawable.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
}

But it does not work and holds still the same color.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Jon not doe xx
  • 533
  • 3
  • 10
  • 20

4 Answers4

0

This how you can change color defined drawable in xml

LayerDrawable shapeRectangle = (LayerDrawable) getDrawable(context, R.drawable.custom_layer);
GradientDrawable gradient = (GradientDrawable) shapeRectangle.findDrawableByLayerId(R.id.shape_rectangle);
gradient.setColor(Color.RED);
Elias Fazel
  • 2,093
  • 16
  • 20
0

Try to use tint to made tint of drawable.

example:

fun getTintDrawable(context:Context, resId: Int, tint: Int): Drawable? {
    val normalDrawable = ContextCompat.getDrawable(context, resId)
    var wrapDrawable = if (normalDrawable == null) null else DrawableCompat.wrap(normalDrawable)

    if (wrapDrawable != null) {
        DrawableCompat.setTint(wrapDrawable, tint)
    }

    return wrapDrawable
}

Sorry that i use kotlin, but rewrite to java could not take so much time. Hope it helps.

BR

Milan Jurkulak
  • 557
  • 3
  • 6
0
@Nullable
public Drawable getTintDrawable(Context context, int resId, int tint) {
    Drawable normalDrawable = ContextCompat.getDrawable(context, resId);
    Drawable wrapDrawable = (normalDrawable == null) ? null : DrawableCompat.wrap(normalDrawable);

    if (wrapDrawable != null) {
        DrawableCompat.setTint(wrapDrawable, tint);
    }

    return wrapDrawable;
}
Milan Jurkulak
  • 557
  • 3
  • 6
0

As requested by @Jonnotdoexx

Same code in Java:

Please note that this function will return null if first if clause fail to execute.

Drawable getTintDrawable(Context context, int resId, int tint) {
    Drawable normalDrawable = ContextCompat.getDrawable(context, resId);
    Drawable wrapDrawable;
    if (normalDrawable != null) 
        wrapDrawble = DrawableCompat.wrap(normalDrawable);
    if (wrapDrawable != null) 
       DrawableCompat.setTint(wrapDrawable, tint);
    return wrapDrawable;
}
Ishaan Kumar
  • 968
  • 1
  • 11
  • 24