button2.setOnClickListener(new OnClickListener() {
......
});
加了個監聽,里面起Timer,定時修改數據。
發現Log一直在打,View無變化。
估計線程出了問題。類似Swing的線程安全問題。
接著Google.....
The best thing is to use Handler with delayed messages.
What I think is happening is you're falling off the UI thread. There
is a single "looper" thread which handles all screen updates. If you
attempt to call "invalidate()" and you're not on this thread nothing
will happen. Try using "postInvalidate()" on your view instead. It'll let you
update a view when you're not in the current UI thread. 解決辦法和我預計的一樣: 1.在Invalidate處調用 postInvalidate,命名上可以參數肯定是把當前的timer線程排隊到UI線程去。不過對于我不是很適用,畢竟UI不希望讓用戶自己去Invalidate 2.既然不能去排隊,那就干脆把自己改造成UI線程吧。借助android.os.Handler final Handler handler = new Handler(); OK!
And Timer works fine, the problem is that a Timer runs in a separate
thread,
and so you are trying to modify a view owned by another thread (the
main
thread that originally created it).
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
root.setName(new Date() + "Root+" );//不一定是顯式的調用修改UI的語句
}
});
}
},1000,3000);