很多新手在启动新线程更新view时会出现
“Only the original thread that created a view hierarchy can touch its views”
既然如此,那就应该让创建view的线程自己更新view。基本思路:创建一个新线程,在该线程中发送一个更新消息给创建view的线程,创建view的线程会处理该消息,即:更新视图。
以下是正确做法
第一步:
/* 启动Thread */
new Thread(mTasks).start();
第二部:
private Runnable mTasks = new Runnable()
{
public void run()
{
while (true)
{
try
{
Thread.sleep(1000);
/* 传送Message给Handler */
mHandler.sendMessage(mHandler.obtainMessage());
//传送数据
/*
Bundle data = new Bundle();
data.putString("aa","ttt");
Message msg = new Message();
msg.setData(data);
mHandler.sendMessage(msg);
*/
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
第三步:
Handler mHandler = new Handler()
{
public void handleMessage(Message msg)
{
super.handleMessage(msg);
view.invalidate();//此处更新view内容
}
};