使用矢量图作为背景的ImageView如何通过编程方式更改backgroundTint?

3
<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 矢量图标。
并且我可以通过以下 xml 将该矢量资产的颜色从红色更改为蓝色。

android:backgroundTint="@color/colorBlue"

但我希望能够通过编程来改变它的颜色。

5个回答

6

使用AppCompatImageView代替ImageView, 因为从API level 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));

我能在 ImageView 上做到,但我的应用程序至少支持 v21 - Aayush Goyal

2

你可以通过编程实现它,像这样:

img.setColorFilter(getResources().getColor(R.color.white));

0

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

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

要了解背景,backgroundTint属性,请阅读此内容:在Android布局xml中,background、backgroundTint、backgroundTintMode属性有什么区别?

最后回答您的问题,如果您真的想要以编程方式更改背景色,请参考此链接:如何以编程方式添加按钮着色?

希望能对您有所帮助!


0

这个问题是相关的,但是回答是关于按钮的。

原始回答由user A.A提供。


你应该使用setBackgroundTintList(ColorStateList list)

点击链接 了解如何创建颜色状态列表资源。

<?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));

0
    imageView.apply {
        setColorFilter(ContextCompat.getColor(context, tintColor), android.graphics.PorterDuff.Mode.MULTIPLY)
        backgroundTintList = ContextCompat.getColorStateList(context, bgTintColor)
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接