Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android ImageButton setColorFilter Not Working

I've look for posts that answer this issue, but none of them are working for me, so I think I have a fundamental misunderstanding of just how it's supposed to work. I have an ImageButton which has a png file applied to it. The png is mostly transparent with the exception of a white arrow. I want to tint the arrow red with setColorFilter:

imageButton.setColorFilter(Color.argb(255, 225, 0, 0));

but this has no affect. I've tried the version of setColorFilter with various Porter-Duff modes, but none of those worked either. Any ideas on what the problem could be or what I might be missing would be greatly appreciated.

like image 886
Ken Avatar asked Feb 26 '15 05:02

Ken


2 Answers

You have to get the Drawable from the button since the setColorFilter you are trying to use (in your setup) apply to those.

ImageButton btn = (ImageButton) myLayout.findViewByID(R.id.my_button);

int mycolor = getResources().getColor(R.color.best_color);

btn.getDrawable().setColorFilter(mycolor, PorterDuff.Mode.SRC_ATOP);

As long as you have the correct reference to a Drawable object,

e.g. textView.getCompoundDrawables()[2].setColorFilter(...);

which in its xml:

<TextView
...
android:drawableLeft="..." 
...
 />

you can use myDrawableObject.setColorFilter() to your full liking.

Edit:

For ImageButton, the drawable for imageButton.getDrawable() correspond to android:src="..." while imageButton.getBackground() correspond to the android:background="..." property. Make sure you call setColorFilter on the correct drawable.

like image 169
Rundel Avatar answered Nov 08 '22 10:11

Rundel


Super late to the party, but just in case anyone else runs into this issue

I've found that if you are creating the ImageView programmatically, use post() before setting color filter

WONT WORK:

ImageView imageView = new ImageView(this);
imageView.setColorFilter(Color.WHITE);

WILL WORK

ImageView imageView = new ImageView(context);

imageView.post(new Runnable() {
    @Override
    public void run() {
        imageView.setColorFilter(Color.WHITE);
    }
});
like image 29
Pythogen Avatar answered Nov 08 '22 10:11

Pythogen