在Android開發過程中,常需要更新界面的UI。而更新UI是要主線程來更新的,即UI線程更新。如果在主線線程之外的線程中直接更新頁面 顯示常會報錯。拋出異常:android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
只有原始創建這個視圖層次(view hierachy)的線程才能修改它的視圖(view)
話不多說,貼出下面的代碼
方法一:
在Activity.onCreate(Bundle savedInstanceState)中創建一個Handler類的實例, 在這個Handler實例的handleMessage回調函數中調用更新界面顯示的函數。
界面:
public class MainActivity extends Activity { private EditText UITxt; private Button updateUIBtn; private UIHandler UIhandler; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); UITxt = (EditText)findViewById(R.id.ui_txt); updateUIBtn = (Button)findViewById(R.id.update_ui_btn); updateUIBtn.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub UIhandler = new UIHandler(); UIThread thread = new UIThread(); thread.start(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } private class UIHandler extends Handler{ @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); Bundle bundle = msg.getData(); String color = bundle.getString("color"); UITxt.setText(color); } } private class UIThread extends Thread{ @Override public void run() { try { Thread.sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } Message msg = new Message(); Bundle bundle = new Bundle(); bundle.putString("color", "黃色"); msg.setData(bundle); MainActivity.this.UIhandler.sendMessage(msg); } } }
更新后:
方法二:利用Activity.runOnUiThread(Runnable)把更新ui的代碼創建在Runnable中,然后在需要更新 ui時,把這個Runnable對象傳給Activity.runOnUiThread(Runnable)。 這樣Runnable對像就能在ui程序中被調用。如果當前線程是UI線程,那么行動是立即執行。如果當前線程不是UI線程,操作是發布到事件隊列的UI 線程.
private class UIThread2 extends Thread { @Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } runOnUiThread(new Runnable() { @Override public void run() { UITxt.setText("黃色"); } });
