Android ImageButton setColorFilter不工作

Android ImageButton setColorFilter不工作,android,android-imagebutton,Android,Android Imagebutton,我一直在寻找能够回答这个问题的帖子,但是没有一篇适合我,所以我想我对它应该如何工作有一个基本的误解。我有一个ImageButton,它应用了一个png文件。png除了白色箭头外,大部分是透明的。我想用setColorFilter将箭头染成红色: imageButton.setColorFilter(Color.argb(255, 225, 0, 0)); 但这没有影响。我尝试过使用各种Porter-Duff模式的setColorFilter版本,但这些模式都不起作用。如果您能提供任何关于问题可

我一直在寻找能够回答这个问题的帖子,但是没有一篇适合我,所以我想我对它应该如何工作有一个基本的误解。我有一个ImageButton,它应用了一个png文件。png除了白色箭头外,大部分是透明的。我想用setColorFilter将箭头染成红色:

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

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

您必须从按钮获取可绘制的图像,因为您尝试使用的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);
只要对可绘制对象有正确的引用

例如textView.getCompoundDrawables()[2].setColorFilter(…)

在其xml中:

<TextView
...
android:drawableLeft="..." 
...
 />

您可以随心所欲地使用myDrawableObject.setColorFilter()

编辑:


对于ImageButton,
ImageButton.getDrawable()
对应于
android:src=“…”
,而
ImageButton.getBackground()
对应于
android:background=“…”
属性。请确保在正确的绘图设备上调用setColorFilter。

派对迟到,但以防其他人遇到此问题

我发现,如果以编程方式创建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);
    }
});

这帮助很大,但我必须使用PorterDuff.Mode.MULTIPLY-drawable.setColorFilter(Color.argb(225,225,0,0),PorterDuff.Mode.MULTIPLY);从视图本身获取可绘制文件非常有用。您提醒我确保引用了正确的可绘制文件,这帮助我解决了问题-我在ImageView中将可绘制文件设置为“背景”,而不是“src”。