Android - button with image - dim image when button disabled
Question
In Android, I have a button that contains an image and text. When the button is disabled, the text is automatically grayed out, but the image stays the same. Is it possible to have the image dimmed when the button is disabled without having two separate images?
Solution 2
Finally got it!
I haven't found a way to do this by setting the image in XML, so have to set it in the code. Here's what I got that works:
Button btnObjects = (Button)this.findViewById(R.id.button_objects);
Bitmap bm = BitmapFactory.decodeResource(context.getResources(), R.drawable.button_image_objects);
if( <button needs to be disabled> )
{
btnObjects.setEnabled(false);
bm = adjustOpacity(bm, 128);
}
else
{
btnObjects.setEnabled(true);
}
btnObjects.setCompoundDrawablesWithIntrinsicBounds(null, new BitmapDrawable(bm), null, null);
//and here's where the magic happens
private Bitmap adjustOpacity(Bitmap bitmap, int opacity)
{
//make sure bitmap is mutable (copy of needed)
Bitmap mutableBitmap = bitmap.isMutable()
? bitmap
: bitmap.copy(Bitmap.Config.ARGB_8888, true);
//draw the bitmap into a canvas
Canvas canvas = new Canvas(mutableBitmap);
//create a color with the specified opacity
int colour = (opacity & 0xFF) << 24;
//draw the colour over the bitmap using PorterDuff mode DST_IN
canvas.drawColor(colour, PorterDuff.Mode.DST_IN);
//now return the adjusted bitmap
return mutableBitmap;
}
OTHER TIPS
In your code, you can also use a ColorFilter, specifically a PorterDuffColorFilter, with a mode of DARKEN
for example.
For the opacity of a Drawable
you can also use setAlpha().
To obtain the Drawable
s (bitmaps, ...) in question button.getCompoundDrawables()
can be used.
I am not sure if this will work, but maybe you want to investigate if it's possible to configure your button's bitmap via a state list, which in turn refers to two drawables of which one refers to a filter. Pretty complex, but if you can't/won't use code for that it may be feasible to do it in XML this way.
In the above scenario i guess you can use selector.xml for the background of your button. You can then use <item android:state_enabled="false" android:color="@color/testcolor3" />
tag accordingly.