關於runOnUiThread()與Handler兩種更新UI的方法


在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回調函數中調用更新界面顯示的函數。
 
界面:
[ html]  
<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(){//方法執行體}})
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM