如何将颜色过滤器应用于StateListDrawable中的特定可绘制对象?

3

看起来StateListDrawable会忽略应用于其包含的可绘制对象上的颜色过滤器。例如:

StateListDrawable sld = new StateListDrawable();
Drawable pressedState = Context.getResources().getDrawable(R.drawable.solid_green);

pressedState.setColorFilter(Color.RED, PorterDuff.Mode.SRC);

sld.addState(new int[] {android.R.attr.state_pressed}, pressedState);
// Other states...

如果您将sld应用于视图的背景,您会期望当它被按下时,该视图的背景会变成纯红色。然而,实际上它会变成绿色 - 即pressedState的颜色,没有任何过滤器应用。
1个回答

5
为了解决这个问题,您需要根据可绘制对象所处的状态,将颜色过滤器应用于StateListDrawable本身。下面是StateListDrawable的扩展实现。
public class SelectorDrawable extends StateListDrawable {

    public SelectorDrawable(Context c) {
        super();

        addState(new int[] {android.R.attr.state_pressed}, c.getResources().getDrawable(R.drawable.solid_green));
        // Other states...
    }

    @Override
    protected boolean onStateChange(int[] states) {
        boolean isClicked = false;
        for (int state : states) {
            if (state == android.R.attr.state_pressed) {
                isClicked = true;
            }
        }

        if (isClicked)
            setColorFilter(Color.RED, PorterDuff.Mode.SRC);
        else
            clearColorFilter();

        return super.onStateChange(states);
    }
}

onStateChange(int[] states) 中的逻辑可以进一步扩展,以测试不仅仅是按下状态,并且可以相应地应用不同的颜色过滤器。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接