设置两个imageview背景alpha只有一个成功

时间:2017-08-30 02:15:19

标签: android background imageview

我在xml中有两个ImageView和一个Button

<ImageView
    android:id="@+id/image1"
    android:layout_width="40dp"
    android:layout_height="40dp"
    android:background="@drawable/backgroud_msg_notify"
    android:src="@mipmap/ic_launcher"
    app:layout_constraintRight_toLeftOf="@+id/guideline"
    android:layout_marginRight="8dp"
    android:layout_marginLeft="8dp"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginTop="8dp" />

<ImageView
    android:id="@+id/image2"
    android:layout_width="40dp"
    android:layout_height="40dp"
    android:background="@drawable/backgroud_msg_notify"
    android:src="@mipmap/ic_launcher"
    android:layout_marginRight="8dp"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginTop="8dp"
    android:layout_marginLeft="8dp"
    app:layout_constraintLeft_toLeftOf="@+id/guideline" />

design

在我的活动中,我这样做:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test_image_view);
    final ImageView imageView1 = (ImageView) findViewById(R.id.image1);
    final ImageView imageView2 = (ImageView) findViewById(R.id.image2);
    Button btn = (Button) findViewById(R.id.button);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            imageView1.getBackground().setAlpha(100);
            imageView2.getBackground().setAlpha(100);
        }
    });
}

但只有imageView1背景alpha改变了,当第一次设置imageview2时,只有imageview2背景改变了。所以我分别复制了背景文件并设置了两个imageview。两个imageview都改变了,为什么?

1 个答案:

答案 0 :(得分:1)

原因是他们为每个背景分享相同的Drawable。调用Drawable的mutate方法可以帮助您:

//Affects only the first one because mutate was called first.
imageView1.getBackground().mutate().setAlpha(100);

阅读本文以了解有关变异drawables的知识: http://www.curious-creature.com/2009/05/02/drawable-mutations/