Temporary color change

In one application that I am developing, I am trying to programmatically create an ImageButton , which is a copy of the selected ImageButton , but the image is colored differently, say red.

If I use PowerDuff.Mode.MULTIPLY :

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

Then even the original ImageButton changes its color to red, since they have the same drawable . Is there a way to apply a filter only to a clone button without using two different drawables ? For example, is it possible to somehow put a coloring layer on top of a clone button without editing drawable ?

Update I install drawable as mutable:

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

This prevents my clone from sharing the state of its drawable with other views .

+6
source share
3 answers
 Drawable buttonBackground = clonebutton.getDrawable(); buttonBackground = buttonBackground.mutate(); buttonBackground.setColorFilter(0xFFFF0000,Mode.MULTIPLY); 

Make this drawable mutable. This operation cannot be undone. may not be sharing his condition with any other range hood. This is especially useful when you need to change the properties of recoverable resources from resources. By default, all drawing instances loaded from the same resource have a common state; if you change the state of one instance, all other instances will receive the same modification. Calling this method on a mutable Drawable will have no effect.

+13
source

On Lollipop you do not need to do this software, i.e. color filters, in general, if you do not want it. You can do this by setting the hue to 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 may not work if you have an unlimited number of colors, but if they are limited, this is a really good option. Check out my blog post for more information .

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

try this: or grab the code below according to your needs

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

button color switching after onclick

0
source

All Articles