錯誤:Only the original thread that created a view hierarchy can touch its views——Handler的使用


在跟隨教程學習到顯示web頁面的html源碼時報錯:Only the original thread that created a view hierarchy can touch its views,通過網上查找資料得知:

android中相關的view和控件不是線程安全的,必須單獨做處理。如果要更新視圖,必須在主線程中更新,不可以在子線程中執行更新的操作。

既然這樣,我們就可以通過Handler對象實現對UI的更新。

 

  Handler的官方描述:


A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue

 


.Handler的使用場合:

 

1、 to schedule messages and runnables to be executed as some point in the future;

      安排messages和runnables在將來的某個時間點執行。

2、 to enqueue an action to be performed on a different thread than your own.

      將action入隊以備在一個不同的線程中執行。即可以實現線程間通信。比如當你創建子線程時,你可以再你的子線程中拿到父線程中創建的Handler對象,就可以通過該對象向父線程的消息隊列發送消息了。由於Android要求在UI線程中更新界面,因此,可以通過該方法在其它線程中更新界面。

 


通過Handler更新UI實例:

 

步驟:

1、創建Handler對象(此處創建於主線程中便於更新UI)。

2、構建Runnable對象,在Runnable中更新界面。

3、在子線程的run方法中向UI線程post,runnable對象來更新UI。

 

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_html);

phtml=(EditText) findViewById(R.id.phtml);
button1=(Button) findViewById(R.id.check_html);
ihtml=(TextView) findViewById(R.id.ihtml);

//創建屬於主線程的handler 
handler=new Handler();

button1.setOnClickListener(new OnClickListener(){

public void onClick(View v) {

new Thread(){ 
public void run(){ 
try {
String path=phtml.getText().toString();
shtml=HtmlService.getHtml(path);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} 
handler.post(runnableUi); 
} 
}.start(); 
//new HtmlSourceAsync(ihtml).execute(path);
}

});
}


// 構建Runnable對象,在runnable中更新界面 
Runnable runnableUi=new Runnable(){ 
@Override 
public void run() { 
//更新界面 
ihtml.setText(shtml); 
} 

};

文章部分引自:http://blog.csdn.net/djx123456/article/details/6325983


免責聲明!

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



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