用Thread和Handler控制ProgressBar的進度
public class HandlerProgressBarAty extends Activity{
private int i = 0;
private ProgressBar mProgressBar;
private android.os.Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
mHandler.postDelayed(mThread, 1000);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pb);
mProgressBar = (ProgressBar) findViewById(R.id.pb);
Button btn_download = (Button) findViewById(R.id.btn_download);
btn_download.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mProgressBar.setVisibility(View.VISIBLE);
mHandler.post(mThread);
}
});
}
private Thread mThread = new Thread(new Runnable(){
@Override
public void run() {
i = i + 10;
mProgressBar.setProgress(i);
Message msg = mHandler.obtainMessage();
msg.arg1 = i;
mHandler.sendMessage(msg);
if(i > 100){
mHandler.removeCallbacks(mThread);
}
}
});
}
可參照 關於Thread和Handler的簡單使用(一)
作者“維王的部落格”