Android中使用Timer配合postInvalidate()重新整理View

來源:互聯網
上載者:User

在一個沒有使用線程的小遊戲中想重新整理一下時間進度,想到用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/android-developers/browse_thread/thread/5baf5a3eaa823b7b?pli=1

http://groups.google.com/group/android-developers/msg/f5765705b8c59d66

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.