Android 更新UI的兩種方法——handler和runOnUiThread()
在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 stubUIhandler = 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 blocke.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() { Toast.makeText(getApplicationContext(), , "Update My UI", Toast.LENGTH_LONG).show(); } });