2011-07-15 72 views
5

我想在按下時更改繪圖的alpha值。 所以我創建了兩個drawable,並將它們放入一個StateListDrawable中,併爲按下的狀態設置了alpha值。但它不起作用。如何在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; 
} 
+0

精氨酸,我正好碰到了同樣的問題!如果我解決問題,會嘗試通知您! –

+0

幫助了我。如果你擴展Drawable,那麼你還需要@Override public boolean isStateful(){ return true; } –

回答

6

這爲我工作

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

這可以工作,但要小心,創建位圖總是對你的記憶有很大的影響 –