您的位置:首页 > 其它

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

2013-12-14 11:23 381 查看
今天写了一个更新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("http://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);
		}
    	
    };
    	
    
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐