android – 将颜色过滤器添加到Drawable使用相同的Drawable更改所有按钮

我有一个屏幕,其中多个按钮使用相同的背景Drawable.我有可重用的代码,我在各种项目中使用它来添加一个OnTouch监听器,在触摸按钮时添加灰色滤色器.这通常可以正常工作,但在这种情况下,当按下任何按钮时,所有按钮都会着色.

我在http://developer.android.com/guide/topics/graphics/2d-graphics.html中看到了一个解释:

Note: Each unique resource in your project can maintain only one
state,no matter how many different objects you may instantiate for
it. For example,if you instantiate two Drawable objects from the same
image resource,then change a property (such as the alpha) for one of
the Drawables,then it will also affect the other.

建议的解决方案是使用TweenAnimation,它似乎不适用于滤色器.

我还看到了Android: Cloning a drawable in order to make a StateListDrawable with filters,建议使用drawable.getConstantState().newDrawable().这似乎没有什么区别.我猜测只要使用相同的物理图像文件,所有Drawables都会受到使用相同资源对任何其他Drawable的更改的影响.

除了创建第二个背景图像以显示按下状态之外,还有什么解决方案?有一个简单的程序化解决方案,我可以添加到我的代码并在每个项目中使用,这将是一件好事.

解决方法

应该适合您的示例:

Drawable buttonBackground = context.getResources().getDrawable(R.drawable.bg);
buttonBackground = buttonBackground.mutate();

//Set your filter here

相关文章

AdvserView.java package com.earen.viewflipper; import an...
ImageView的scaleType的属性有好几种,分别是matrix(默认)...
文章浏览阅读8.8k次,点赞9次,收藏20次。本文操作环境:win1...
文章浏览阅读1.2w次,点赞15次,收藏69次。实现目的:由main...
文章浏览阅读3.8w次。前言:最近在找Android上的全局代理软件...
文章浏览阅读2.5w次,点赞17次,收藏6次。创建项目后,运行项...