Android ImageButton setColorFilter不起作用

7

我已经查看了一些解决此问题的帖子,但它们都对我无效,所以我认为我对它应该如何工作有一个基本的误解。我有一个ImageButton,它应用了一个png文件。这个png文件大部分是透明的,只有一个白色箭头。我想使用setColorFilter将箭头着色为红色:

imageButton.setColorFilter(Color.argb(255, 225, 0, 0));

但这没有任何影响。我已经尝试了使用各种Porter-Duff模式的setColorFilter版本,但这些都没有起作用。如果您有任何关于问题可能是什么或者我可能遗漏了什么的想法,将不胜感激。

2个回答

13

你需要从按钮中获取Drawable,因为你正在尝试使用的setColorFilter(在你的设置中)会应用于它们。

ImageButton btn = (ImageButton) myLayout.findViewByID(R.id.my_button);

int mycolor = getResources().getColor(R.color.best_color);

btn.getDrawable().setColorFilter(mycolor, PorterDuff.Mode.SRC_ATOP);

只要您正确引用了Drawable对象,例如:textView.getCompoundDrawables()[2].setColorFilter(...);,那么就可以对其进行颜色过滤。此外,在xml中也可以实现此效果。
<TextView
...
android:drawableLeft="..." 
...
 />

你可以使用 myDrawableObject.setColorFilter() 来完全按照你的喜好进行操作。

编辑:

对于 ImageButton,imageButton.getDrawable() 的 drawable 对应于 android:src="...",而 imageButton.getBackground() 对应于 android:background="..." 属性。确保在正确的 drawable 上调用 setColorFilter。


1
这很有帮助,但我必须使用PorterDuff.Mode.MULTIPLY - drawable.setColorFilter(Color.argb(225, 225, 0, 0), PorterDuff.Mode.MULTIPLY); - Ken
从视图本身获取可绘制对象非常顺利。 - Nestor Ledon
你提醒我确保我引用了正确的drawable,帮助我找出了问题所在——我将我的drawable设置为ImageView上的“background”而不是“src”。 - beyondtheteal

2

虽然来晚了,但如果有人遇到这个问题

我发现如果你是在程序中创建ImageView,请在设置颜色过滤器之前使用post()

不起作用:

ImageView imageView = new ImageView(this);
imageView.setColorFilter(Color.WHITE);

将会工作

ImageView imageView = new ImageView(context);

imageView.post(new Runnable() {
    @Override
    public void run() {
        imageView.setColorFilter(Color.WHITE);
    }
});

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