在一個沒有使用線程的小遊戲中想刷新一下時間進度,想到用Timer。於是寫了一段代碼︰ nStartRoundTime = System.currentTimeMillis(); nT1 = new Timer(); nT1.schedule(new TimerTask(){ //計畫營運時間間隔 public void run(){ refreshTimePaint(); //過3秒調用一下refreshTimePaint() } },0,3000); public void refreshTimePaint(){ invalidate(); //使用invalidate();刷新 System.out.println(System.currentTimeMillis()); System.out.println(nGameState); } 同時我也將System.currentTimeMillis()列印在View上。 營運一下,發現並不是預期那樣, System.out.println的結果在Log裡面都有變化,但是View卻沒有回應。 不但View上面沒有被刷新,甚至連原來的觸屏事件都沒有反映了。 去網上查了一下,得到的一些解釋有這些︰ The best thing is to use Handler with delayed messages. 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). 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. 於是把refreshTimePaint()的代碼改成︰ public void refreshTimePaint(){ this.postInvalidate(); //使用postInvalidate();刷新 System.out.println(System.currentTimeMillis()); System.out.println(nGameState); } 這樣View就能自動刷新了~~~ 這裡有幾個網頁做參考︰ http://stackoverflow.com/questions/522800/android-textview-timer http://groups.google.com/group/a ... f5a3eaa823b7b?pli=1 http://groups.google.com/group/a ... sg/f5765705b8c59d66 資料來源: http://blog.csdn.net/lixinso |
希望藉由這個網誌,讓更多人了解Android其實有很多東西可以玩,並不比iphone差,看看網路上的諷刺短片 " I don't care!",雖然誇張了一點,但也說明了很多人盲目的追求而已
2010年12月18日 星期六
Android中使用Timer配合postInvalidate()刷新View
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言