【发布时间】:2011-07-15 09:51:46
【问题描述】:
我想在按下时更改可绘制对象的 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;
}
【问题讨论】:
-
Arg,我遇到了同样的问题!如果我修复它,会尽量让你知道!
-
帮助了我。如果你扩展 Drawable 那么你还需要 @Override public boolean isStateful() { return true; }
标签: android alpha-transparency