Android开发学习之路--Drawable mutations

  时间过得很快,明天终于可以拿到房子了,交完这次房租,也可以成为房东了,看看博客也好久没有更新了,最近一直在整机器人,也没有太多时间整理博客。
  今天下午和同事一起遇到了一个问题,就是明明没有改变一个控件的alpha值,但是这个控件的透明度居然变了。甚是奇怪之余,大神在stackoverflow上去提了问题,最后也有另外的大神给了正确的回复。
  最终我们知道了是android的Drawable mutations的一些小细节问题,具体的可以参考一篇讲解Drawable mutations很好的文章
  其实是android为了节省内存,把资源给共享了,如果两个控件的drawable使用了相同的资源,可能是相同的图片资源,可能是相同的颜色,或者其他。
  可能还是不是非常理解,那我们就来个例子吧,首先我们新建个activity的layout文件,如下:

     <Button
        android:id="@+id/test1"
        android:layout_width="80dp"
        android:layout_height="100dp"
        android:background="@android:color/holo_green_dark"
        android:text="tes1"/>

    <Button
        android:id="@+id/test2"
        android:layout_width="100dp"
        android:layout_height="80dp"
        android:layout_marginTop="10dp"
        android:background="@android:color/holo_green_dark"
        android:text="test2" />

    <SeekBar
        android:id="@+id/seekBar_1"
        android:layout_marginTop="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="255"/>

  这里省略了,只显示需要的控件,其中test1和test2的background是一样的,然后seeker是之后为了改变透明度使用。那就开始写测试的代码吧:

    Button test1 = (Button)findViewById(R.id.test1);
    Button test2 = (Button)findViewById(R.id.test2);

    SeekBar seekBar = (SeekBar)findViewById(R.id.seekBar_1);
    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                test1.getBackground().setAlpha(255-progress);
                test2.invalidate();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }

  这里通过拖动seekbar,然后改变button1的alpha值,这里没有设置button2的alpha,只是button2刷新了下。可以看下效果:

  显然我们没有设置button2的background,那为什么button2的背景透明度也变换了呢?其实就是如上所说的资源共享了,两个button,我们都用了同一个的颜色,所以系统把公用了同一个颜色的资源,那么当我们改变button1的颜色的时候,button2的alpha值也会跟着改变。
  但是很多时候我们确实需要只改变一个控件的状态而不是改变两个,那要怎么处理呢?这就是这里要讲的mutations了,mutation意为变化,突变的意思,这里如果使用mutation的话,那么就会只改变一个颜色了,那么我们修改i下代码:

  test1.getBackground().mutate().setAlpha(255-progress);

  修改设置alpha的方法,使用mutate()方法,然后运行看下效果:

  如上图,我们得到了很好的实践。

原文地址:https://www.cnblogs.com/wuyida/p/6299938.html