我正在尝试使用LayerDrawable作为源来扩展ImageView。每一层都包含一个StateListDrawable,其中一个是ShapeDrawable,另一个是从资源加载的Drawable。
在用户按下时,ShapeDrawable从青色渐变为白色,并且图标可从其原始颜色(白色)绘制为可绘制的颜色过滤器,将其转换为相同的青色。
图标始终保持原始颜色相同,但ShapeDrawable渐变为白色。我已经从图标中删除了白色状态,并且出现了青色,因此我假设它在StateListDrawable的某个地方出现问题。我也删除了进入和退出淡入淡出持续时间而没有任何成功。
代码如下
public class DrawerItemIcon extends ImageView {
private static final String ITEM_ENABLED_COLOR = "#1ABC9C";
private int mIconResource;
private StateListDrawable mCircleDrawable;
private StateListDrawable mIconDrawable;
public DrawerItemIcon(Context context, int iconResource) {
super(context);
mIconResource = iconResource;
init();
}
private void init() {
setDuplicateParentStateEnabled(true);
setImageDrawable(getLayers());
}
private LayerDrawable getLayers() {
Drawable[] layers = new Drawable[2];
layers[1] = getCircleDrawable();
layers[0] = getIconDrawable();
return new LayerDrawable(layers);
}
private Drawable getCircleDrawable() {
mCircleDrawable = new StateListDrawable();
mCircleDrawable.addState(new int[]{android.R.attr.state_pressed},getPressedShapeCircleDrawable());
mCircleDrawable.addState(new int[]{android.R.attr.state_enabled}, getEnabledShapeCircleDrawable());
mCircleDrawable.setEnterFadeDuration(500);
mCircleDrawable.setExitFadeDuration(500);
return mCircleDrawable;
}
private ShapeDrawable getPressedShapeCircleDrawable() {
ShapeDrawable bgDrawable = new ShapeDrawable();
bgDrawable.setShape(new OvalShape());
bgDrawable.getPaint().setStyle(Paint.Style.STROKE);
bgDrawable.getPaint().setStrokeWidth(4);
bgDrawable.getPaint().setColor(Color.WHITE);
return bgDrawable;
}
private ShapeDrawable getEnabledShapeCircleDrawable() {
ShapeDrawable bgDrawable = new ShapeDrawable();
bgDrawable.setShape(new OvalShape());
bgDrawable.getPaint().setStyle(Paint.Style.STROKE);
bgDrawable.getPaint().setStrokeWidth(4);
bgDrawable.getPaint().setColor(Color.parseColor(ITEM_ENABLED_COLOR));
return bgDrawable;
}
public Drawable getIconDrawable() {
mIconDrawable = new StateListDrawable();
mIconDrawable.addState(new int[]{android.R.attr.state_pressed}, getPressedIconDrawable());
mIconDrawable.addState(new int[]{android.R.attr.state_enabled}, getEnabledIconDrawable());
mIconDrawable.setEnterFadeDuration(500);
mIconDrawable.setExitFadeDuration(500);
return mIconDrawable;
}
private Drawable getPressedIconDrawable() {
return getResources().getDrawable(mIconResource);
}
private Drawable getEnabledIconDrawable() {
Drawable selectedDrawable = getResources().getDrawable(mIconResource);
selectedDrawable.setColorFilter(
new PorterDuffColorFilter(Color.parseColor(ITEM_ENABLED_COLOR), PorterDuff.Mode.MULTIPLY));
return selectedDrawable;
}
}
答案 0 :(得分:1)
这是因为那个可绘制的常态。解决此问题的方法是在.mutate()
方法中添加getEnabledIconDrawable()
来电。
... getResources().getDrawable(mIconResource).mutate();
有关常量状态的更多信息,请访问:http://www.curious-creature.com/2009/05/02/drawable-mutations/
在其他地方回答,但会放在这里供将来参考。