1. 程式人生 > >Android開發學習之路--Drawable mutations

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()方法,然後執行看下效果:

  如上圖,我們得到了很好的實踐。