android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a v

android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views

android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a v_第1张图片

原因:在子线程中更改UI操作导致的错误

解决办法:用handler去创建一个子线程执行耗时操作,然后回到主线程更改UI界面

例如:

package com.mw.mwreaderdemo;

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 MainActy extends Activity {
	private Button btn;
	private TextView textView;
	private Handler handler=null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //创建属于主线程的handler
        handler=new Handler();
        btn=(Button)findViewById(R.id.btn);
        textView=(TextView)findViewById(R.id.textView);
        btn.setOnClickListener(new BtnOnClieckListener());
    }
    //为按钮添加监听器
    class BtnOnClieckListenerimplements OnClickListener{
		@Override
		public void onClick(View v) {
		
			new Thread(){
				public void run(){	
					/**
					在这里写耗时操作例如网络请求之类的
					**/

					handler.post(runnableUi); 
					}					
			}.start();						
		}
    	
    } 

   // 构建Runnable对象,在runnable中更新界面
    Runnable   runnableUi=new  Runnable(){
		@Override
		public void run() {
			//在这里写更新UI的操作
			textView.setText("Hello World");
		}
    	
    };
    	
    
}

你可能感兴趣的:(android)