2013-01-08 42 views
2

全部:在另一個線程中訪問UI視圖不*會導致崩潰。爲什麼?

我真的不好意思幫忙。我認爲下面的代碼 - 被修改,以便直接訪問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); 
        } 
       }); 
      } 

回答

6

如今,ProgressBar具有邏輯,允許setProgress()在後臺線程被調用。它會檢查您正在使用的線程,並根據需要自行執行Runnablepost()。你可以在the source code看到這個。

+0

謝謝,謝謝,謝謝,這讓我瘋狂!我用TextView嘗試了同樣的事情,並得到了我期待的錯誤。 –

+1

@MichaelRogers:「我期待的錯誤」? :-) – CommonsWare

相關問題