1.XML文件添加两个ProcessBar组件,分别选择水平/圆形进度条
<ProgressBar android:id="@+id/pb1"
android:layout_width="match_parent"
android:max="100"
style="@android:style/Widget.ProgressBar.Horizontal"
android:layout_height="wrap_content"/>
<ProgressBar android:id="@+id/pb2"
android:layout_width="wrap_content"
style="@android:attr/progressBarStyleLarge"
android:layout_height="wrap_content"/>
2.Activity文件定义两个进度条,一个用于表示进度的int变量,一个处理消息的Handler类对象
private ProgressBar hp;
private ProgressBar cp;
private int mProgressStatus =0;
private Handler mHandler;//用于处理消息的Handler对象
3.Oncreate()方法获取进度条,通过匿名内部类实例化Handler类对象,重写其handleMessage方法,实现耗时操作未完成的更新进度,以及完成时设置进度条不再显示
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
hp =(ProgressBar) findViewById(R.id.pb1);
cp= (ProgressBar)findViewById(R.id.pb2);
mHandler= new Handler(){
@Override
public void handleMessage(Message msg){
if (msg.what==0x111){
hp.setProgress(mProgressStatus);
}
else {
Toast.makeText(MainActivity.this,
"finish", Toast.LENGTH_SHORT).show();
hp.setVisibility(View.GONE);
cp.setVisibility(View.GONE);
}
}
};
4.开启一个耗时线程,调用sendMessage方法发送处理消息
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
mProgressStatus= doWork();
Message m=new Message();
if(mProgressStatus<100){
m.what=0x111;
mHandler.sendMessage(m);
}
else {
m.what=0x110;
mHandler.sendMessage(m);
break;
}
}
}
private int doWork()
{
mProgressStatus+= Math.random()*10;
try{
Thread.sleep(200);
} catch(InterruptedException e){
e.printStackTrace();
}
return mProgressStatus;
}
}).start();
}
网友评论