需要为图像视图设置色调…我使用它的方式如下:

imageView.setColorFilter(R.color.blue,android.graphics.PorterDuff.Mode.MULTIPLY);

但这并没有改变……


当前回答

在android中以编程方式设置图像视图的色调

我有两个方法为android:

1)

imgView.setColorFilter(context.getResources().getColor(R.color.blue));

2)

 DrawableCompat.setTint(imgView.getDrawable(),
                     ContextCompat.getColor(context, R.color.blue));

我希望我能帮到大家:-)

其他回答

在android中以编程方式设置图像视图的色调

我有两个方法为android:

1)

imgView.setColorFilter(context.getResources().getColor(R.color.blue));

2)

 DrawableCompat.setTint(imgView.getDrawable(),
                     ContextCompat.getColor(context, R.color.blue));

我希望我能帮到大家:-)

大多数答案指的是使用setColorFilter,这不是最初的问题。

用户@Tad的答案是正确的,但它只适用于API 21+。

要设置所有Android版本的色调,使用ImageViewCompat:

ImageViewCompat.setImageTintList(imageView, ColorStateList.valueOf(yourTint));

注意,在这种情况下,yourTint必须是一个“颜色int”。如果你有一个像r。color这样的颜色资源。蓝色,你需要先加载颜色int:

ContextCompat.getColor(context, R.color.blue);

对我来说,这个代码是有效的。我使用它与卡片和图像视图,但我认为它可以在任何视图改变他们的色调颜色。 cardBookmark是我的cardView。

var cardDrawable: Drawable = binding.cardBookmark.background
cardDrawable = DrawableCompat.wrap(cardDrawable)
DrawableCompat.setTint(cardDrawable, resources.getColor(R.color.shuffleColor))
binding.cardBookmark.background = cardDrawable

@Hardik说得对。代码中的另一个错误是在引用xml定义的颜色时。你只将id传递给setColorFilter方法,而你应该使用id来定位颜色资源,并将资源传递给setColorFilter方法。重写下面的原始代码。

如果这一行在你的活动中:

imageView.setColorFilter(getResources().getColor(R.color.blue), android.graphics.PorterDuff.Mode.MULTIPLY);

否则,你需要引用你的主活动:

Activity main = ...
imageView.setColorFilter(main.getResources().getColor(R.color.blue), android.graphics.PorterDuff.Mode.MULTIPLY);

注意,其他类型的资源也是如此,比如整数、bool、维度等。除了string,你可以直接在你的Activity中使用getString(),而不需要首先调用getResources()(不要问我为什么)。

否则,您的代码看起来很好。(虽然我还没有研究setColorFilter方法太多…)

Random random=new Random;
ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
ColorFilter cf = new PorterDuffColorFilter(Color.rgb(random.nextInt(255), random.nextInt(255), random.nextInt(255)),Mode.OVERLAY);

imageView.setImageResource(R.drawable.ic_bg_box);
imageView.setColorFilter(cf);