Android使用Drawable资源之使用ClipDrawable资源 实现进入条

时间:2020-11-26 04:29:23

以前我自定义的进度条(就是咱们现在工程中用的)是从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/back_submit_default"
android:gravity="left" > </clip>

2、在界面布局文件layout中引用上面定义的这个ClipDrawable,比如

clip_layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<View
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="52dp"
android:layout_gravity="center_vertical"
android:background="@drawable/clip" >
</View> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="@+id/button"
android:onClick="stop_ProgressBar"
android:layout_gravity="center_horizontal" />
</LinearLayout>

3、然后在代码中这么写就可以实现随意控制进度条的进度了:

<span style="color:#000000;">        setContentView(R.layout.clip_layout);
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);
}
}
};
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);</span>

停止进行条:

if(null != timer)
{
timer.cancel(); timer = null;
}

特别说明几个问题:

1、clip.xml这个文件中有几个属性, android:clipOrientation="horizontal"表示水平或竖直;android:gravity="left"表示从左面开始,或从右面开始,或从上面开始,或从下面开始。

2、当然如果是要进度条那么引用的这个图片必然是.9.png格式的啦。



用这种方法可以自定义各种进度条了,非常方便。建议自定义的时候要把你定义的进度条封装成独立的类,这样方便修改和维护。

另外还可以用这种方法实现图片的徐徐展开效果:见http://blog.csdn.net/lee576/article/details/7827676

demo  下载 :http://download.csdn.net/detail/q610098308/9542750