2017-08-30 6 views
1

私は、XMLで2 ImageViewと1 Buttonあります設定された2つのImageViewの背景アルファ唯一の成功

@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); 
     } 
    }); 
} 

しかし、唯一:私の活動で

<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

、私はこれを行うにimageView1背景アルファ変更、最初にimageview2を設定すると、imageview2の背景のみが変更されました。だから私は背景ファイルをコピーし、それぞれ2つの画像ビューを設定します.2つの画像ビューがすべて変更されました、なぜですか?

答えて

1

なぜなら、それぞれの背景に同じDrawableを共有しているからです。ドロウアブルのmutateメソッドを呼び出すと、ここであなたを助ける:

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

は、ドローアブルを変異についての学習のためにこれを読む: http://www.curious-creature.com/2009/05/02/drawable-mutations/

関連する問題