可绘制单例

Is drawable a singleton

有一个行为不确定它是否应该如此。 如果视图背景中使用的drawable是与其他视图共享的一个实例,如何更改个体的颜色?

有 R.drawable.circle_shape 作为:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
   android:shape="oval">
    <corners android:radius="10dip"/>
    <solid android:color="#cccccc"/>
</shape>

在一个片段中用作两个实例

    <ImageView
      android:id="@+id/circle_1”
      android:layout_width="22dp"
      android:layout_height="22dp"
      android:gravity="center"
      android:layout_gravity="center"
      android:background="@drawable/circle_shape"
      android:shadowRadius="10.0"
                        />

  <ImageView
      android:id="@+id/circle_2”
      android:layout_width="22dp"
      android:layout_height="22dp"
      android:gravity="center"
      android:layout_gravity="center"
      android:background="@drawable/circle_shape"
      android:shadowRadius="10.0"
                        />

另一个用途是用于其他片段中的列表项模板

    <ImageView
      android:id="@+id/listItem_image”
      android:layout_width="22dp"
      android:layout_height="22dp"
      android:gravity="center"
      android:layout_gravity="center"
      android:background="@drawable/circle_shape"
      android:shadowRadius="10.0"
                        />

当我改变实例 c1 的圆圈颜色时,我注意到 c2 和 listItem_image 也改变了颜色。

View c1 = (View) findViewById(R.id. circle_1);                                
c1.setBackgroundResource(R.drawable.circle_shape);  // with or without this it will still affect the other ImageView which also uses R.drawable.circle_shape as background

((GradientDrawable) c1.getBackground()).setColor(intColor);
((GradientDrawable) c1.getBackground()).setStroke(0, Color.TRANSPARENT);

不是真正的单例,但你的猜测方向是正确的。当您获得一个可绘制对象时,它会与其他可绘制对象共享状态。这就是为什么当您修改其中之一时,您会修改所有与其共享状态的可绘制对象。

您需要做的是mutate drawable,以便创建一个新状态。在您的情况下,它看起来像这样:

GradientDrawable drawable = ((GradientDrawable) c1.getBackground()).mutate();
drawable.setColor(intColor);
drawable.setStroke(0, Color.TRANSPARENT);

第一行创建一个新状态,它允许接下来的两行仅更改此特定可绘制对象的状态。