1. 程式人生 > >Android用ClipDrawable自定義各種進度條(包括豎直和水平)

Android用ClipDrawable自定義各種進度條(包括豎直和水平)

這裡兩年前在eoe寫的一個帖子,這次也搬過來統一管理:

==============

以前我自定義的進度條是從android的原始碼中扒出來的一個XML,然後把裡面的圖片給替換了。一直不知道它的具體原理是什麼。


今天得空研究了一下,發現它的原理其實就是用的android提供的一個叫ClipDrawable的類實現的。
於是我就繼續深入研究ClipDrawable的用法,研究的結果讓我很開心,發現這個類可以很容易實現各種自定義進度條的效果。
ClipDrawable類繼承自Drawable,具體用法如下:
1、先自定義一個XML(命名為clip.xml),放在Drawable資料夾下面:
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <clip xmlns:android="http://schemas.android.com/apk/res/android"
  3.     android:clipOrientation="horizontal"
  4.     android:drawable="@drawable/green_progress_drawable"
  5.     android:gravity="left" >
  6. </clip>
複製程式碼 2、在介面佈局檔案layout中引用上面定義的這個ClipDrawable,比如:
  1.     <View
  2.         android:id="@+id/image"
  3.         android:layout_width="fill_parent"
  4.         android:layout_height="22dip"
  5.         android:layout_centerInParent="true"
  6.         android:background="@drawable/clip" >
  7.     </View>
複製程式碼 3、然後在程式碼中這麼寫就可以實現隨意控制進度條的進度了:
  1. View imageview = findViewById(R.id.image);
  2. final ClipDrawable drawable = (ClipDrawable) imageview.getBackground();
  3. final Handler handler = new Handler() {
  4.    public void handleMessage(Message msg) {
  5.     if (msg.what == 0x1233) {
  6.      drawable.setLevel(drawable.getLevel() + 30);
  7.     }
  8.    }
  9.   };
  10. final Timer timer = new Timer();
  11.   timer.schedule(new TimerTask() {
  12.    @Override
  13.    public void run() {
  14.     Message msg = new Message();
  15.     msg.what = 0x1233;
  16.     handler.sendMessage(msg); 
  17.     if (drawable.getLevel() >= 10000 || isFinishing()) {
  18.      timer.cancel();
  19.     }
  20.    }
  21.   }, 0, 50);
複製程式碼 到這裡自定義進度條就完成了。
特別說明幾個問題:
1、clip.xml這個檔案中有幾個屬性, android:clipOrientation="horizontal"表示水平或豎直;android:gravity="left"表示從左面開始,或從右面開始,或從上面開始,或從下面開始。
2、當然如果是要進度條那麼引用的這個圖片必然是.9.png格式的啦。

用這種方法可以自定義各種進度條了,非常方便。建議自定義的時候要把你定義的進度條封裝成獨立的類,這樣方便修改和維護。

===============================
如果你覺得幫到了你,請給作者打賞一口飯吃: