閱讀803 返回首頁    go 阿裏雲 go 技術社區[雲棲]


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

今天寫了一個更新UI的小例子,沒想到出了log打印了這樣一個錯誤:Only the original thread that created a view hierarchy can touch its views。goolgle了一下找到了原因。

原來android中相關的view和控件不是線程安全的,我們必須單獨做處理。這裏借此引出Handler的使用。

通過Handler更新UI實例:

步驟:

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

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

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

package djx.android;

import djx.downLoad.DownFiles;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class downLoadPractice extends Activity {
	private Button button_submit=null;
	private TextView textView=null;
	private String content=null;
	private Handler handler=null;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //創建屬於主線程的handler
        handler=new Handler();
        
        button_submit=(Button)findViewById(R.id.button_submit);
        textView=(TextView)findViewById(R.id.textView);
        button_submit.setOnClickListener(new submitOnClieckListener());
    }
    //為按鈕添加監聽器
    class submitOnClieckListener implements OnClickListener{
		@Override
		public void onClick(View v) {
//本地機器部署為服務器,從本地下載a.txt文件內容在textView上顯示			
			final DownFiles df=new DownFiles("https://192.168.75.1:8080/downLoadServer/a.txt");
			textView.setText("正在加載......");
			new Thread(){
				public void run(){	
					content=df.downLoadFiles();		
					handler.post(runnableUi); 
					}					
			}.start();						
		}
    	
    } 

   // 構建Runnable對象,在runnable中更新界麵
    Runnable   runnableUi=new  Runnable(){
		@Override
		public void run() {
			//更新界麵
			textView.setText("the Content is:"+content);
		}
    	
    };
    	
    
}


最後更新:2017-04-03 12:53:45

  上一篇:go 等比例縮放圖片
  下一篇:go 軟件工程---軟件需求分析