How to set alpha value for drawable in a StateListDrawable?
Asked Answered
D

1

6

I want to change a drawable's alpha value when it is pressed. So I create two drawables and put them in a StateListDrawable and set the alpha value for the pressed state. But it just doesn't work.

StateListDrawable content = new StateListDrawable();
Drawable contentSelected = this.getResources().getDrawable(
R.drawable.content_background);
contentSelected.mutate().setAlpha(100);

Drawable contentNormal = this.getResources().getDrawable(R.drawable.content_background);

content.addState(new int[] { android.R.attr.state_pressed }, contentSelected);
content.addState(new int[] { android.R.attr.state_enabled }, contentNormal);

ImageButton button = (ImageButton) view.findViewById(R.id.content_thumbnail);
button.setImageDrawable(content);

Update: My final solution is to create a subclass of BitmapDrawable like this, and change the alpha value in the onStateChange() method.

public AlphaAnimatedDrawable(Resources res, Bitmap bitmap) {
    super(res, bitmap);
    this.setState(new int[] { android.R.attr.state_pressed, android.R.attr.state_selected,
            android.R.attr.state_enabled });
}

private static final int PRESSED_ALPHA = 180;
private static final int REGULAR_ALPHA = 255;

@Override
protected boolean onStateChange(int[] states) {

    for (int state : states) {
        if (state == android.R.attr.state_pressed) {
            setAlpha(PRESSED_ALPHA);
        } else if (state == android.R.attr.state_selected) {
            setAlpha(REGULAR_ALPHA);
        } else if (state == android.R.attr.state_enabled) {
            setAlpha(REGULAR_ALPHA);
        }
    }
    return true;
}
Daggerboard answered 15/7, 2011 at 9:51 Comment(2)
Arg, I just hit the same problem! Will try to let you know if I fix it!Demott
Helped me. If you extend Drawable then you need also @Override public boolean isStateful() { return true; }Beforetime
D
6

This worked for me

  StateListDrawable drawable = new StateListDrawable();

  Bitmap enabledBitmap = ((BitmapDrawable)mIcon).getBitmap();

  // Setting alpha directly just didn't work, so we draw a new bitmap!
  Bitmap disabledBitmap = Bitmap.createBitmap(
      mIcon.getIntrinsicWidth(),
      mIcon.getIntrinsicHeight(), Config.ARGB_8888);
  Canvas canvas = new Canvas(disabledBitmap);

  Paint paint = new Paint();
  paint.setAlpha(126);
  canvas.drawBitmap(enabledBitmap, 0, 0, paint);

  BitmapDrawable disabled = new BitmapDrawable(mContext.getResources(), disabledBitmap);

  drawable.addState(new int[] { -android.R.attr.state_enabled}, disabled);
  drawable.addState(StateSet.WILD_CARD, mIcon);
Demott answered 19/9, 2011 at 21:34 Comment(1)
This works but be careful, creating bitmaps is always a big dent on your memorySayles

© 2022 - 2024 — McMap. All rights reserved.