2
我真的不好意思幫忙。我認爲下面的代碼 - 被修改,以便直接訪問UI小部件(進度條)而不是使用處理程序 - 會導致交叉線程異常。但事實並非如此。所以,我的問題是,這個代碼不應該崩潰嗎?如果沒有,那麼我什麼時候需要使用處理程序?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
progress = 0;
progressBar = (ProgressBar) findViewById(R.id.progressbar);
progressBar.setMax(200);
//---do some work in background thread---
new Thread(new Runnable()
{
public void run()
{
//ó-do some work hereó-
while (progressStatus < 200)
{
progressStatus = doSomeWork();
progressBar.setProgress(progressStatus); // not on UI thread
//ó-Update the progress baró- // so shouldn't it crash?
// handler.post(new Runnable()
// {
// public void run() {
// progressBar.setProgress(progressStatus);
// }
// });
}
//---hides the progress bar---
handler.post(new Runnable()
{
public void run()
{
//---0 - VISIBLE; 4 - INVISIBLE; 8 - GONE---
progressBar.setVisibility(View.GONE);
}
});
}
謝謝,謝謝,謝謝,這讓我瘋狂!我用TextView嘗試了同樣的事情,並得到了我期待的錯誤。 –
@MichaelRogers:「我期待的錯誤」? :-) – CommonsWare