Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Temporarily change drawable color

Tags:

java

android

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.

like image 897
Vektor88 Avatar asked Mar 28 '13 12:03

Vektor88


1 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.

like image 119
Triode Avatar answered Oct 11 '22 23:10

Triode