异常信息:
01-10 00:46:22.039: E/AndroidRuntime(1621): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
点击事件中修改一个TextView的颜色:
public void changeColor (View v){
new Thread(new Runnable() {
@Override
public void run() {
//子线程更新UI
main_tv.setTextColor(Color.RED);
}
}).start();
}
子线程是无法直接修改UI的我们可以子线程里通过handler.setMessage(),来通知UI线程(主线程) 修改UI
public void changeColor (View v){
final Thread thread =new Thread(new Runnable() {
@Override
public void run() {
//子线程更新UI
//
// if(Looper.myLooper()==Looper.getMainLooper()){
// main_tv.setTextColor(Color.RED);
// }
Message msg =Message.obtain();
msg.what=1;
Handler.sendMessage(msg ); //发消息
}
});
thread.start();
}
接收处理消息:
public class MainActivity extends Activity {
private String TAG ="MainActivity";
Handler Handler = new Handler(){
public void handleMessage(android.os.Message msg) {
if(msg.what==1){
main_tv.setTextColor(Color.RED);
}
};
};