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

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

但这并没有改变……


当前回答

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)用于设置和删除:

其他回答

在棒棒糖开始,有一个方法叫做imageview# setImageTintList(),你可以使用…其优点是,它需要一个ColorStateList,而不是只有一个颜色,从而使图像的色调状态感知。

在之前的lollipop设备上,你可以通过着色drawable来获得相同的行为,然后将它设置为ImageView的image drawable:

ColorStateList csl = AppCompatResources.getColorStateList(context, R.color.my_clr_selector);
Drawable drawable = DrawableCompat.wrap(imageView.getDrawable());
DrawableCompat.setTintList(drawable, csl);
imageView.setImageDrawable(drawable);

不是确切的答案,而是一个更简单的选择:

在图像上方放置另一个视图 您可以随意更改视图的alpha值(以编程方式)以获得所需的效果。

以下是其中的一个片段:

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="@dimen/height120"
        android:contentDescription="@string/my_description"
        android:scaleType="fitXY"
        android:src="@drawable/my_awesome_image"/>

    <View
        android:layout_width="match_parent"
        android:layout_height="@dimen/height120"
        android:alpha="0.5"
        android:background="@color/my_blue_color"/>
</FrameLayout>

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

因为第一个答案对我不起作用:

//get ImageView
ImageView myImageView = (ImageView) findViewById(R.id.iv);

//colorid is the id of a color defined in values/colors.xml
myImageView.setImageTintList(ColorStateList.valueOf(ContextCompat.getColor(getApplicationContext(), R.color.colorid)));

这似乎只适用于API 21+,但对我来说这不是问题。不过,您可以使用ImageViewCompat来解决这个问题。

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

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

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