Handler ProgessBar
通过Handler 主线程设置ProgerssBar控件的值, 一个异步的线程Runnable 控制ProgerssBar的值,并把值封装好通过Message 传递给Handler.
package com.xtl.test2;
import javax.security.auth.callback.Callback;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ProgressBar;
import android.widget.TextView;
public class myProgressBar extends Activity{
private ProgressBar pb = null;
private TextView tvPersent = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.progressbar);
pb = (ProgressBar)this.findViewById(R.id.pb);
tvPersent = (TextView)this.findViewById(R.id.tvPersent);
Thread thread = new Thread(myRun);
//开始异步执行
thread.start();
}
Handler handler = new Handler(){
@Override
public void handleMessage(Message arg0) {
//将要执行的线程放入到队列当中
pb.setProgress(arg0.arg1);
tvPersent.setText(arg0.arg1 + "%");
pb.setSecondaryProgress(arg0.arg1 + 10);
}
};
Runnable myRun = new Runnable() {
int progressValue = 0;
public void run() {
while(true){
// TODO Auto-generated method stub
//拿到主线程Handler的Message
Message msg = handler.obtainMessage();
//将进度值作为消息的参数包装进去,进度自加1
msg.arg1 = progressValue ++;
//将消息发送给主线程的Handler
handler.sendMessage(msg);
//这个例子是反复循环,实际项目中可能没必要
if(progressValue>100){
progressValue = 0;
}
try{
//为了让您看到进度滚动效果,放慢进度上升的速度
Thread.sleep(300);
}
catch(InterruptedException e){
e.printStackTrace();
}
}
}
};
}