android.view.ViewRoot$CalledFromWrongThreadException 異常的解決方案 * 更新時間: 2011-07-21

來源:互聯網
上載者:User
在android平台下,進行多線程編程時,經常需要在主線程之外的一個單獨的線程中進行某些處理,然後更新使用者介面顯示。但是,在主線線程之外的線程中直接更新頁面顯示的問題是:系統會報這個異常,android.view.viewroot$calledfromwrongthreadexception: only the original thread that created a view hierarchy can touch its views. (只有原始建立這個視圖層次(view hierachy)的線程才能修改它的視圖(view)。)。

  也就是說必須在程式的主線程(也就是ui線程)中進行更新介面顯示的工作。可以採用下面的方法之一來解決:

解決方案1:在activity.oncreate(bundle savedinstancestate)中建立一個handler類的執行個體, 在這個handler執行個體的handlemessage回呼函數中調用更新介面顯示的函數。例如:

  

public class ExampleActivity extends Activity {Handler h = null;@overridepublic void onCreate(Bundle savedinstancestate){h = new Handler(){@overridepublic void handleMessage(Message msg){// call update gui method.}};}}


  在其它的函數中,利用 send族或post族函數向這個h發送或郵寄訊息即可。


解決方案2:利用activity.runonuithread(runnable)

  把更新ui的代碼建立在runnable中,然後在需要更新ui時,把這個runnable對象傳給activity.runonuithread(runnable)。 這樣runnable對像就能在ui程式中被調用。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.