我有一个自定义 ImageView ,它应该可以通过编程方式或从布局中设置图标的颜色。 这行得通。
假设我在黑色背景上使用了一个白色图标。
然后,如果在应用程序的另一个地方可以绘制相同的图标并反转颜色,白色背景上的黑色图标。然后只有以前使用过的图标保持其原始颜色。而且我无法从布局或编程方式更改它。相同的 Activity 但不同的 fragment 。
这是类(class)。
public class IconView extends ImageView {
public IconView(Context context) {
this(context, null);
}
public IconView(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.iconViewStyle);
}
public IconView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.IconView, defStyle, 0);
int color = attributes.getColor(R.styleable.IconView_icon_color, Color.WHITE);
ColorFilter cf = new PorterDuffColorFilter(color, PorterDuff.Mode.SRC_IN);
if (getDrawable() != null) getDrawable().setColorFilter(cf);
attributes.recycle();
}
public void setIconColor(int color) {
getDrawable().setColorFilter(color, PorterDuff.Mode.SRC_IN);
}
}
我是不是做错了什么,或者 android 可能会以某种方式重用可绘制对象,一旦绘制它们就会保持原样(看起来很奇怪)!
最佳答案
我知道另一个答案已被选为正确答案,但在我看来你遇到的问题与答案暗示的不同。如果您在同一个 Activity 中使用同一张图片(尤其是来自资源的图片),那么在您应用滤色器时所有图片都会被修改。这是因为 res 中的可绘制对象是不可变的,并且将共享相同的状态。为避免这种情况,请使用 getDrawable().mutate().setColorFilter(color, PorterDuff.Mode.SRC_IN)
。
mutate()
的文档包含更多相关信息。
关于android - 如果再次使用相同的可绘制对象,带有 colorFilter 的自定义 ImageView 将保持相同的过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30464205/