进度条是一种非常实用的组件,下面我们来学习一下如何实用进度条
android提供了几个进度条的样式:
Widget.ProgressBar.Horizontal
Widget.ProgressBar.Small
Widget.ProgressBar.Large
Widget.ProgressBar.Inverse
Widget.ProgressBar.Small.Inverse
Widget.ProgressBar.Large.Inverse
ProgressBar组件的特有xml属性:
下面通过案例来学习ProgressBar
(1)编写布局文件 activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ProgressBar
android:id="@+id/progress1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:progress="20"
android:max="100"
android:layout_margin="20dp"
style="@android:style/Widget.ProgressBar.Horizontal"/>
<TextView
android:id="@+id/proText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="100dp"
android:text="当前进度:20%"/>
</LinearLayout>
(2)编写MainActivity.java
由于要更新主线程UI,因此需要定义Handler来更新主线程
package com.example.progressbar;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.widget.ProgressBar;
import android.widget.TextView;
public class MainActivity extends Activity {
private ProgressBar progressBar = null; //定义ProgressBar
private TextView textView = null; //定义TextView
private static final int PROGRESS = 0x1;
private int mProgressStatus =20; //当前进度
private Handler mHandler = new Handler(); //定义Handler,用于更新主线程UI
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取布局组件
this.progressBar = (ProgressBar) findViewById(R.id.progress1);
this.textView = (TextView) findViewById(R.id.proText);
//开启线程
new Thread(new Runnable() {
@Override
public void run() {
while (mProgressStatus < 100) {
mProgressStatus = doWork();
//更新进度条和进度内容
mHandler.post(new Runnable() {
public void run() {
progressBar.setProgress(mProgressStatus);
textView.setText("当前进度:"+mProgressStatus+"%");
}
});
}
}
}).start();
}
private int doWork(){
mProgressStatus = mProgressStatus+1;
try{
Thread.sleep(100);
}catch(Exception e){
e.printStackTrace();
}
return mProgressStatus;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
运行后,效果如下: