public class ProgressBarTest extends Activity {
private int progress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.progress_bar);
final Handler handler = new Handler();
progress = 0;
final ProgressBar pb = (ProgressBar) findViewById(R.id.progressbar);
new Thread(new Runnable() {
public void run() {
while (progress < 10) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
progress++;
}
handler.post(new Runnable() {
@Override
public void run() {
pb.setVisibility(View.GONE);
}
});
}
}).start();
}
}
為什麼不能把 pb.setVisibility(View.GONE) 放在第一個 Runnable 內部類中?下面的代碼程序崩潰。
new Thread(new Runnable() {
public void run() {
while (progress < 10) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
progress++;
pb.setVisibility(View.GONE);
}
}
}
當 setVisibility 語句執行時程序崩潰。
因為
handler.post(new Runnable() {
@Override
public void run() {
pb.setVisibility(View.GONE);
}
});
是通知主線程(也就是UI線程去刷新界面),而後面你沒有通知主線程,只是在子線程中刷新,android是線程不安全的,所以只有UI線程可以刷新界面,所以子線程刷新造成了crash