阅读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 软件工程---软件需求分析