代码之家  ›  专栏  ›  技术社区  ›  thinuwan

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

  •  3
  • thinuwan  · 技术社区  · 8 年前
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:backgroundTint="@color/colorRed"
        android:background="@drawable/ic_delete"/>
    


    我可以通过xml将向量资源的颜色从红色更改为蓝色,如下所示。

    android:backgroundTint="@color/colorBlue"
    

    5 回复  |  直到 6 年前
        1
  •  6
  •   Muthukrishnan Rajendran    8 年前

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

    这样改变你的图像视图,

    <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"/>
    

    要这样设置色调,

    imageView.setSupportBackgroundTintList(ContextCompat.getColorStateList(this, R.color.colorBlue));
    
        2
  •  3
  •   Cœur Gustavo Armenta    6 年前

    通过编程,您可以这样实现:

    img.setColorFilter(getResources().getColor(R.color.white));
    
        3
  •  0
  •   theAndDev    8 年前

    首先,背景和src是ImageView的不同属性。 android:src="drawable"

    app:srcCompat="drawable"

    为了了解背景,请阅读backgroundTint属性: What is the difference between background, backgroundTint, backgroundTintMode attributes in android layout xml?

    How to add button tint programmatically

    希望有帮助!

        4
  •  0
  •   LeoColman    8 年前

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

    原始答案 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));
    

    contextInstance Context

    使用AppCompat

    btnTag.setSupportButtonTintList(ContextCompat.getColorStateList(Activity.this, R.color.colorPrimary));
    
        5
  •  0
  •   nAkhmedov    5 年前
        imageView.apply {
            setColorFilter(ContextCompat.getColor(context, tintColor), android.graphics.PorterDuff.Mode.MULTIPLY)
            backgroundTintList = ContextCompat.getColorStateList(context, bgTintColor)
        }