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

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

但这并没有改变……


当前回答

不要使用波特达夫。模式, 使用setColorFilter()它适用于所有情况。

ImageView imageView = (ImageView) listItem.findViewById(R.id.imageView);
imageView.setColorFilter(getContext().getResources().getColor(R.color.msg_read));

其他回答

大多数答案指的是使用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

试试这个。它应该适用于支持库支持的所有Android版本:

public static Drawable getTintedDrawableOfColorResId(@NonNull Context context, @NonNull Bitmap inputBitmap, @ColorRes int colorResId) {
    return getTintedDrawable(context, new BitmapDrawable(context.getResources(), inputBitmap), ContextCompat.getColor(context, colorResId));
}

public static Drawable getTintedDrawable(@NonNull Context context, @NonNull Bitmap inputBitmap, @ColorInt int color) {
    return getTintedDrawable(context, new BitmapDrawable(context.getResources(), inputBitmap), color);
}

public static Drawable getTintedDrawable(@NonNull Context context, @NonNull Drawable inputDrawable, @ColorInt int color) {
    Drawable wrapDrawable = DrawableCompat.wrap(inputDrawable);
    DrawableCompat.setTint(wrapDrawable, color);
    DrawableCompat.setTintMode(wrapDrawable, PorterDuff.Mode.SRC_IN);
    return wrapDrawable;
}

你可以使用上面的任何一个来使它工作。

你可以在这里阅读DrawableCompat文档中更多有趣的特性。

我发现我们可以为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>

在我使用的java中

imageView.setImageTintList(ColorStateList.valueOf(ContextCompat.getColor(context, R.color.red)));