Android 以编程方式在图层列表中设置颜色

Android set colors in layer-list programmatically

我有这个可绘制对象:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:id="@+id/circle">
        <shape android:shape="oval">
            <size android:width="120dp" android:height="120dp"></size>
            <stroke android:width="4dp"/>
        </shape>
    </item>

    <item
        android:id="@+id/person"
        android:top="16dp"
        android:bottom="16dp"
        android:left="16dp"
        android:right="16dp">
        <bitmap android:src="@drawable/ic_person_48dp" />
    </item>

</layer-list>

我将其设置为回收站视图中的项目:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="150dp"
    android:layout_height="150dp"
    android:layout_margin="10dp"
    android:clickable="true"
    android:gravity="center"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/person_icon"/>

</LinearLayout>

我想在绑定方法中为每个单元格设置不同的颜色:

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
  ImageView imageView = holder.personImageView;

  // How do I grab the circle shape and person bitmap from the image view
  // and set the colors for this cell?
}

我需要这个才能在 api 17 岁及以上工作。

试试这个:

final LayerDrawable layerDrawable = holder.personImageView.getDrawable().mutate();
layerDrawable.getDrawable(index).mutate().setColorFilter(color, PorterDuff.Mode.SRC_IN);

您必须调用 drawable 的 mutate() 方法,否则颜色会随着 LayerDrawable 的每次迭代而改变。