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

标签 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

在我的 Activity 中,我这样做:

@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都变了,为什么?

最佳答案

原因是他们为每个背景共享相同的 Drawable。调用 mutate Drawable 的方法将在此处帮助您:

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

关于android - 设置两个imageview背景alpha只有一个成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45950875/

相关文章:

android - 当应用程序对象被系统杀死时清除返回堆栈

android - fragment 中的 TextView.setText() 导致应用程序崩溃

validation - CSS3 背景渐变不验证,谁能告诉我为什么?里面的代码示例

css 图片

安卓.view.InflateException : on writing a custom imageView

android - Google Play 应用内结算免费赠送一件商品

android - WebView 用户代理

android - 缩放背景图像以包装布局内容

Android - Imageview 在所有屏幕分辨率的中心

Android如何使用矩阵获取 ImageView 的边界