使用 Vector Asset 以编程方式更改 ImageView 的 backgroundTint 作为背景

Programmatically change backgroundTint of ImageView with Vector Asset for background

<ImageView
    android:id="@+id/imageView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:backgroundTint="@color/colorRed"
    android:background="@drawable/ic_delete"/>

如上所述,我为 ImageView 背景添加了一个 Android VectorAsset。
我可以通过 xml 将 Vector Asset 的颜色从红色更改为蓝色,如下所示。

android:backgroundTint="@color/colorBlue"

但我想以编程方式更改其颜色。

首先,background 和 src 是 ImageView 的不同属性。 您是否要将图像设置为 ImageView?首先你必须使用 属性: android:src="drawable"

如果您使用矢量资源,则需要使用 属性:app:srcCompat="drawable"

要了解背景,请阅读 backgroundTint 属性:

并最终以编程方式回答您对背景色调的问题,如果这是您真正想要的,那么这里是 link

希望对您有所帮助!

问题是相关的,但答案是按钮。

user A.A

的原始回答

你应该使用 setBackgroundTintList(ColorStateList list)

按照此 link 了解如何创建颜色状态列表资源。

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:color="#your_color_here" />
</selector>

然后使用

加载它
setBackgroundTintList(contextInstance.getResources().getColorStateList(R.color.your_xml_name));

其中 contextInstanceContext

的实例

使用 AppCompat

btnTag.setSupportButtonTintList(ContextCompat.getColorStateList(Activity.this, R.color.colorPrimary));

您可以使用 AppCompatImageView 而不是 ImageView,因为 API 级别 21 支持 setBackgroundTintList,如果您使用 AppCompatImageView,您可以更改使用 setSupportBackgroundTintList.

的色调

所以像这样改变你的 ImageView,

<android.support.v7.widget.AppCompatImageView
    android:id="@+id/imageView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:backgroundTint="@color/colorRed"
    android:background="@drawable/ic_delete"/>

这样您就可以像这样调用 setSupportBackgroundTintList 来设置色调,

imageView.setSupportBackgroundTintList(ContextCompat.getColorStateList(this, R.color.colorBlue));

您可以通过编程方式实现它:

img.setColorFilter(getResources().getColor(R.color.white));
    imageView.apply {
        setColorFilter(ContextCompat.getColor(context, tintColor), android.graphics.PorterDuff.Mode.MULTIPLY)
        backgroundTintList = ContextCompat.getColorStateList(context, bgTintColor)
    }