我遇到了同样的问题,并且进一步解决了这个问题。但是,唯一的问题是您无法在xml中指定NavStateListDrawable,因此必须通过代码设置UI元素的背景。然后必须重写onStateChange方法,以确保每次更改主可绘制对象的级别时,您还要更新子级别列表的级别。
构造NavStateListDrawable时,必须传递要显示的图标级别。
public class NavStateListDrawable extends StateListDrawable {
private int level;
public NavStateListDrawable(Context context, int level) {
this.level = level;
//int stateChecked = android.R.attr.state_checked;
int stateFocused = android.R.attr.state_focused;
int statePressed = android.R.attr.state_pressed;
int stateSelected = android.R.attr.state_selected;
addState(new int[]{ stateSelected }, context.getResources().getDrawable(R.drawable.nav_btn_pressed));
addState(new int[]{ statePressed }, context.getResources().getDrawable(R.drawable.nav_btn_selected));
addState(new int[]{ stateFocused }, context.getResources().getDrawable(R.drawable.nav_btn_focused));
addState(new int[]{-stateFocused, -statePressed, -stateSelected}, context.getResources().getDrawable(R.drawable.nav_btn_default));
}
@Override
protected boolean onStateChange(int[] stateSet) {
boolean nowstate = super.onStateChange(stateSet);
try{
LayerDrawable defaultDrawable = (LayerDrawable)this.getCurrent();
LevelListDrawable bar2 = (LevelListDrawable)defaultDrawable.findDrawableByLayerId(R.id.nav_icons);
bar2.setLevel(level);
}catch(Exception exception)
{
}
return nowstate;
}
}
对于所有不同的导航按钮可绘制状态,我都有类似以下内容。
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/top_bar_default" >
</item>
<item android:id="@+id/nav_icons" android:bottom="0dip">
<level-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:maxLevel="0" >
<bitmap
android:src="@drawable/top_bar_icon_back"
android:gravity="center" />
</item>
<item android:maxLevel="1" >
<bitmap
android:src="@drawable/top_bar_icon_nav"
android:gravity="center" />
</item>
<item android:maxLevel="2" >
<bitmap
android:src="@drawable/top_bar_icon_settings"
android:gravity="center" />
</item>
<item android:maxLevel="3" >
<bitmap
android:src="@drawable/top_bar_icon_search"
android:gravity="center" />
</item>
</level-list>
</item>
</layer-list>
我本来将其发布为一个问答,但是看到您问了这个问题之后,您就可以开始了。注意,这为您省去了许多xml文件定义。我从大约50-100个xml定义下降到大约4个!