Android中使用Timer配合postInvalidate()刷新View

10 篇文章 0 订阅
5 篇文章 0 订阅

在一个没有使用线程的小游戏中想刷新一下时间进度,想到用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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值