使用矢量资源以编程方式更改 ImageView 的 backgroundTint 作为背景

thi*_*wan 3 android imageview android-layout android-xml

<ImageView
    android:id="@+id/imageView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:backgroundTint="@color/colorRed"
    android:background="@drawable/ic_delete"/>
Run Code Online (Sandbox Code Playgroud)

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

android:backgroundTint="@color/colorBlue"
Run Code Online (Sandbox Code Playgroud)

但我想以编程方式改变它的颜色。

Mut*_*ran 5

而不是使用ImageView您可以使用AppCompatImageView,因为setBackgroundTintList从 API 级别 21 开始支持,如果您使用,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"/>
Run Code Online (Sandbox Code Playgroud)

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

imageView.setSupportBackgroundTintList(ContextCompat.getColorStateList(this, R.color.colorBlue));
Run Code Online (Sandbox Code Playgroud)