我想改变一个可拉伸的阿尔法值时,它被按下。
所以我创建了两个Drawables并将它们放在StateListDrawable中,并为按下的状态设置alpha值。但这不管用。

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

更新:
我的最终解决方案是创建一个子类bitmapdrawable,如下所示,
并更改onStateChange()方法中的alpha值。
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;
}

最佳答案

这对我有效

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

08-17 09:10