Home » Java » Temporarily change drawable color

Temporarily change drawable color

Posted by: admin December 28, 2021 Leave a comment

Questions:

In one app I’m developing I’m trying to programatically create an ImageButton that is a copy of the selected ImageButton, but the image is colorized in a different way, let’s say red.

If I use the PowerDuff.Mode.MULTIPLY:

clonebutton.getDrawable().setColorFilter(0xFFFF0000,Mode.MULTIPLY);

Then even the original ImageButton changes its color to red since they share the same drawable. Is there a way to apply the filter only on the clonebutton without using two different drawables? For instance is it possible in some way to put a colorize layer on top of clonebutton without editing the drawable?

Update
I set the drawable as mutable:

Drawable d = swipebutton.getDrawable();
d.mutate();
d.setColorFilter(0xFFFF0000,Mode.MULTIPLY);
swipebutton.setImageDrawable(d);

This prevents my clonebutton to share the state of its drawable to other views.

Answers:
Drawable buttonBackground = clonebutton.getDrawable();
buttonBackground = buttonBackground.mutate();
buttonBackground.setColorFilter(0xFFFF0000,Mode.MULTIPLY);

Make this drawable mutable. This operation cannot be reversed. A
mutable drawable is guaranteed to not share its state with any other
drawable. This is especially useful when you need to modify properties
of drawables loaded from resources. By default, all drawables
instances loaded from the same resource share a common state; if you
modify the state of one instance, all the other instances will receive
the same modification. Calling this method on a mutable Drawable will
have no effect.

###

On Lollipop you don’t have to do this programmatic, i.e. colorfilters, at all if you don’t want to. You can do it just by setting a tint on an xml drawable.

<?xml version="1.0" encoding="utf-8"?>
<bitmap
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/ic_back"
    android:tint="@color/red_tint"/>

This might not work if you have an unlimiited number of colors but if they are limited this is a really good option. Check out my blog post for more information.

###

Drawable d=clonebutton.getDrawable()
d.setColorFilter(0xFFFF0000,Mode.MULTIPLY);
clonebutton.setDrawable(d);

try this: or take the below code as per your need

 switch(v.getId())
{
case R.id.bt1:
    Drawable d=b11.getBackground();
    d.setColorFilter(Color.CYAN,PorterDuff.Mode.MULTIPLY);

    b11.setBackgroundDrawable(d);
    b12.setBackgroundResource(android.R.drawable.btn_default);
break;

case R.id.bt2:
//b2.getBackground().setColorFilter(Color.CYAN,PorterDuff.Mode.MULTIPLY);
Drawable dd=b12.getBackground();
dd.setColorFilter(Color.CYAN,PorterDuff.Mode.MULTIPLY);

b12.setBackgroundDrawable(dd);
b11.setBackgroundResource(android.R.drawable.btn_default);
break;
}

switching color of buttons after onclick