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;
}
精氨酸,我正好碰到了同樣的問題!如果我解決問題,會嘗試通知您! –
幫助了我。如果你擴展Drawable,那麼你還需要@Override public boolean isStateful(){ return true; } –