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

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

但这并没有改变……


当前回答

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

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

其他回答

更新: @ADev在他的回答中有更新的解决方案,但他的解决方案需要更新的支持库- 25.4.0或以上。


你可以改变色调,很容易在代码中通过:

imageView.setColorFilter(颜色。Argb (255, 255, 255, 255));//白色色调

如果你想要色彩鲜艳的话

imageView.setColorFilter(ContextCompat.getColor(context, R.color.COLOR_YOUR_COLOR), android.graphics.PorterDuff.Mode.MULTIPLY);

对于可绘制的向量

imageView.setColorFilter(ContextCompat.getColor(context, R.color.COLOR_YOUR_COLOR), android.graphics.PorterDuff.Mode.SRC_IN);
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);

kotlin中的一个扩展函数,用于设置和取消设置着色。

fun ImageView.setTint(@ColorRes color: Int?) {
  if (color == null) {
    ImageViewCompat.setImageTintList(this, null)
  } else {
    ImageViewCompat.setImageTintList(this, ColorStateList.valueOf(ContextCompat.getColor(context, color)))
}}

用法:yourImageView.setTint(R.color.white)用于设置和删除:

这对我很有效

mImageView.setColorFilter(ContextCompat.getColor(getContext(), R.color.green_500));

我发现我们可以为tint attr使用颜色选择器:

mImageView.setEnabled(true);

activity_main.xml:

<ImageView
    android:id="@+id/image_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_arrowup"
    android:tint="@color/section_arrowup_color" />

section_arrowup_color.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@android:color/white" android:state_enabled="true"/>
    <item android:color="@android:color/black" android:state_enabled="false"/>
    <item android:color="@android:color/white"/>
</selector>