安卓:克隆绘制,以使StateListDrawable与过滤器过滤器、StateListDrawable

2023-09-12 07:07:44 作者:单身闯天下

我试图做一个总体框架的功能,使任何可绘制变得突出时的 pressed /聚焦/选择的/ etc

I'm trying to make a general framework function that makes any Drawable become highlighted when pressed/focused/selected/etc.

我的函数将被拉伸,并返回一个StateListDrawable,其中默认状态是绘制对象本身,而国家对于 android.R.attr.state_ pressed 是一样的绘制,只需使用应用了滤镜 setColorFilter

My function takes a Drawable and returns a StateListDrawable, where the default state is the Drawable itself, and the state for android.R.attr.state_pressed is the same drawable, just with a filter applied using setColorFilter.

我的问题是,我无法克隆的绘制和做它的一个单独的实例应用了过滤器。这里是我想要实现的:

My problem is that I can't clone the drawable and make a separate instance of it with the filter applied. Here is what I'm trying to achieve:

StateListDrawable makeHighlightable(Drawable drawable)
{
    StateListDrawable res = new StateListDrawable();

    Drawable clone = drawable.clone(); // how do I do this??

    clone.setColorFilter(0xFFFF0000, PorterDuff.Mode.MULTIPLY);
    res.addState(new int[] {android.R.attr.state_pressed}, clone);
    res.addState(new int[] { }, drawable);
    return res;
}

如果我不克隆然后过滤器显然是适用于这两个州。我试着用打变异(),但它并不能帮助。

If I don't clone then the filter is obviously applied to both states. I tried playing with mutate() but it doesn't help..

任何想法?

更新:

接受的答案确实是克隆一个绘制。因为我一般功能上的不同的问题未能它并没有帮助我,虽然。看来,当你添加一个可绘制到StateList,它就失去了所有过滤器。

The accepted answer indeed clones a drawable. It didn't help me though because my general function fails on a different problem. It seems that when you add a drawable to a StateList, it loses all its filters.

推荐答案

请尝试以下操作:

Drawable clone = drawable.getConstantState().newDrawable();