我想使用选择器在未启用图标时将其灰显。似乎这样的东西应该起作用(具有白色背景):
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" >
android:alpha="0.5"
</item>
<item android:state_enabled="true" >
android:alpha="1"
</item>
</selector>
Run Code Online (Sandbox Code Playgroud)
但它会在运行时导致 java.lang.NumberFormatException。我也尝试过“0.5f”。同样的错误。
这类似于Is there a way to set drawable's Alpha using XML? 但我特别询问 NumberFormatException。顺便说一句,我也尝试使用 0 到 255 之间的整数值。我得到了同样的错误。
我想在按下时更改drawable的alpha值.所以我创建了两个drawable并将它们放在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);
Run Code Online (Sandbox Code Playgroud)
更新:我的最终解决方案是像这样创建BitmapDrawable的子类,并更改方法中的alpha值onStateChange().
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) { …Run Code Online (Sandbox Code Playgroud)