因此,我创建了一个具有两个图像的StateListDrawable:
1. 背景图片 2. 当项目被按下时的图片
到目前为止,使用以下代码实现了以上要求:
NinePatchDrawable background = (NinePatchDrawable) context.getResources().getDrawable(R.drawable.calendar_item);
Drawable backgroundFocus = context.getResources().getDrawable(R.drawable.calendar_focus);
int stateFocused = android.R.attr.state_focused;
int statePressed = android.R.attr.state_pressed;
StateListDrawable sld = new StateListDrawable();
sld.addState(new int[]{ stateFocused, statePressed}, backgroundFocus);
sld.addState(new int[]{-stateFocused, statePressed}, backgroundFocus);
sld.addState(new int[]{-stateFocused}, background);
return sld;
但我想做一些额外的事情。我希望用户能够传递一个颜色,以便将其用于显示背景。因此,背景变量必须是可变的,但它必须基于九宫格可绘制对象。
所以我想我可以这样做:
background.setColorFilter(Color.RED, PorterDuff.Mode.DST_IN);
需要将Color.RED替换为用户选择的颜色。
但是似乎并没有起作用。九宫格图案被完美地创建,但是颜色过滤器未被应用。
我还尝试了其他PoterDuff.Mode:
- SRC
- SRC_ATOP
- DST_IN
- ...
如果您知道我做错了什么或者有其他解决方法,请告诉我!:-)
Kr,
Dirk