在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回調函數中調用更新界面顯示的函數。
界面:
<span style="font-size:14px;">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線程中。
FusionField.currentActivity.runOnUiThread(new Runnable(){
public void run(){//方法執行體}})