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 语句时程序崩溃。