Android 更新UI的兩種方法——handler和runOnUiThread()

來源:互聯網
上載者:User

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();                  }                    });  


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.