ProgressBar 控件
(一)、概述
进度条(ProgressBar) 是UI中非常实用的控件,类名: ProgressBar,用于动态显示某个比较耗时操作的进度,可避免因操作时间长,使用户感觉程序失去了响应,从而提高用户的使用体验。
有两种进度条:默认的进度条(不断地转圈)和水平进度条
XML属性 说明 max 设置进度条的最大值 progess 设置已完成的进度值 secondaryProgress 设置第二进度条 progressDrawable 设置进度条的轨道的绘制形式 progressBarStyle 设置进度条样式 progressBarStyleHorizontal 水平进度条样式 progressBarStyleLarge 大进度条样式 progressBarStyleSmall 小进度条样式
progressBar 的 Style 有如下值:
horizontal 水平进度条 inverse 不断跳跃、选转的进度条 large 大进度条 large.inverse 不断跳跃、旋转的大进度条 small 小进度条 small.inverse 不断跳跃、旋转的小进度条
说明:
1、以上的 style 属性值前面都要加上如下的前缀:
@android:style/Widget.ProgressBar.,例如:
@android:style/Widget.PorgressBar.Large : 大进度条
2、Widget:我们所称的UI中的控件,也称为小部件。
实例:
MainActibity.java中的代码:
package com.jxust.day03_07;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ProgressBar;
public class MainActivity extends ActionBarActivity {
ProgressBar mProgressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
setListener();
}
private void setListener() {
findViewById(R.id.btnDownload).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
new Thread() {
public void run() {
mProgressBar.setProgress(0);
for (int i = 0; i <= 100; i++) {
mProgressBar.setProgress(i);
SystemClock.sleep(10); // 使当前线程休眠10毫秒
// 是当前线程休眠10毫秒有两种办法:上面的那种是不需要捕获异常的,Tread是需要捕获异常的,因为Tread的休眠有可能会被打断
/*
* try{ Thread.sleep(10); }
* catch(InterruptedException e){
* e.printStackTrace(); }
*/
}
};
}.start();
}
});
}
private void initView() {
mProgressBar = (ProgressBar) findViewById(R.id.pb2);
mProgressBar.setProgress(0);
}
}
activity_main.xml中的代码
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <RelativeLayout android:id="@+id/rlBar1" android:layout_width="wrap_content" android:layout_height="wrap_content" > <ProgressBar android:id="@+id/pb1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RelativeLayout> <RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/rlBar1" android:layout_marginTop="10dp" > <ProgressBar android:id="@+id/pb2" style="@android:style/Widget.ProgressBar.Horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:max="100" android:progress="30" /> <Button android:layout_marginTop="25dp" android:id="@+id/btnDownload" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Download File" /> </RelativeLayout> </RelativeLayout>