Android用ClipDrawable自定義各種進度條(包括豎直和水平)
阿新 • • 發佈:2019-01-22
這裡兩年前在eoe寫的一個帖子,這次也搬過來統一管理:
==============
以前我自定義的進度條是從android的原始碼中扒出來的一個XML,然後把裡面的圖片給替換了。一直不知道它的具體原理是什麼。
今天得空研究了一下,發現它的原理其實就是用的android提供的一個叫ClipDrawable的類實現的。
於是我就繼續深入研究ClipDrawable的用法,研究的結果讓我很開心,發現這個類可以很容易實現各種自定義進度條的效果。
ClipDrawable類繼承自Drawable,具體用法如下:
1、先自定義一個XML(命名為clip.xml),放在Drawable資料夾下面:
-
<?xml version="1.0" encoding="utf-8"?>
-
<clip xmlns:android="http://schemas.android.com/apk/res/android"
-
android:clipOrientation="horizontal"
-
android:drawable="@drawable/green_progress_drawable"
-
android:gravity="left" >
- </clip>
-
<View
-
android:id="@+id/image"
-
android:layout_width="fill_parent"
-
android:layout_height="22dip"
-
android:layout_centerInParent="true"
-
android:background="@drawable/clip" >
- </View>
-
View imageview = findViewById(R.id.image);
- final ClipDrawable drawable = (ClipDrawable) imageview.getBackground();
-
final Handler handler = new Handler() {
-
public void handleMessage(Message msg) {
-
if (msg.what == 0x1233) {
-
drawable.setLevel(drawable.getLevel() + 30);
-
}
-
}
-
};
-
final Timer timer = new Timer();
-
timer.schedule(new TimerTask() {
-
@Override
-
public void run() {
-
Message msg = new Message();
-
msg.what = 0x1233;
- handler.sendMessage(msg);
-
if (drawable.getLevel() >= 10000 || isFinishing()) {
-
timer.cancel();
-
}
-
}
- }, 0, 50);
特別說明幾個問題:
1、clip.xml這個檔案中有幾個屬性, android:clipOrientation="horizontal"表示水平或豎直;android:gravity="left"表示從左面開始,或從右面開始,或從上面開始,或從下面開始。
2、當然如果是要進度條那麼引用的這個圖片必然是.9.png格式的啦。
用這種方法可以自定義各種進度條了,非常方便。建議自定義的時候要把你定義的進度條封裝成獨立的類,這樣方便修改和維護。
===============================
如果你覺得幫到了你,請給作者打賞一口飯吃: