安卓:克隆绘制,以使StateListDrawable与过滤器 [英] Android: Cloning a drawable in order to make a StateListDrawable with filters

查看:750
本文介绍了安卓:克隆绘制,以使StateListDrawable与过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做一个总体框架的功能,使任何可绘制变得突出时的 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();

这篇关于安卓:克隆绘制,以使StateListDrawable与过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆