Skip to content

Instantly share code, notes, and snippets.

@maxep
Last active Mar 6, 2018
Embed
What would you like to do?
[Android] Add gray filter when disabling an ImageButton
import android.content.Context;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageButton;
public class MyImageButton extends ImageButton{
public MyImageButton(Context context) {
super(context);
}
public MyImageButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyImageButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
Drawable background = getBackground();
Drawable drawable = getDrawable();
if (enabled) {
if (background != null)
background.setColorFilter(null);
if (drawable != null)
background.setColorFilter(null);
}
else {
if (background != null)
background.setColorFilter(Color.LTGRAY, PorterDuff.Mode.SRC_IN);
if (drawable != null)
drawable.setColorFilter(Color.LTGRAY, PorterDuff.Mode.SRC_IN);
}
}
}
@hassan-nasr
Copy link

hassan-nasr commented Mar 6, 2018

please correct the

        if (drawable != null)
            background.setColorFilter(null);

to

        if (drawable != null)
            drawable.setColorFilter(null);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment