進度條 ProgressBar的簡單運用
阿新 • • 發佈:2018-10-31
進度條 ProgressBar
1 常用屬性
style=”?android:attr/progressBarStyleHorizontal” 預設為圓形
android:progress=”33”
android:max=”100”
執行緒休眠
Thread.sleep(100);//拋異常
SystemClock.sleep(100);//不會拋異常
2 執行緒注意事項:
不能在主執行緒中執行耗時的操作,只能在子執行緒中操作
另外,在子執行緒中不能操作主執行緒中的控制元件(ProgressBar除外)
SubThread->MainThread 錯誤
3 Handler(重點、面試問得比較多)
用於執行緒之間的通訊,比如:主執行緒與子執行緒
.4 執行緒小結
SubThread->MainThread 錯誤
SubThread->Handler->MainThread 正確
public class MainActivity extends AppCompatActivity {
private ProgressBar pb_main_pb1;
private int progress=0;
private TextView tv_main_tv1;
private MyHandler myHandler=new MyHandler();
private int code=1;
private class MyHandler extends Handler{
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (code==msg.what){
progress++;
pb_main_pb1.setProgress(progress);
tv_main_tv1.setText(progress+"%" );
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pb_main_pb1=this.findViewById(R.id.pb_main_pb1);
tv_main_tv1=this.findViewById(R.id.tv_main_tv1);
}
public void setProgress(View view) {
if (0==progress){
new MyThread().start();
}
}
private class MyThread extends Thread{
@Override
public void run() {
super.run();
while(true){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (progress==100){
progress=0;
break;
}
Message msg=new Message();
msg.what=1;
myHandler.sendMessage(msg);
}
}
}
}