繁体   English   中英

android中的倒计时器

[英]countdown timer in android

我有一个带有一些值的表,我想每10秒更新一次UI(值)。 我想向用户展示倒数计时器以了解将要发生的事情......但它会崩溃。 我用于此的代码如下所示:

tv2_r7= (TextView) this.findViewById(R.id.textView2_r7);

    final Timer timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        int i = 10;
        public void run() {
            tv2_r7.setText(String.valueOf(i));
            i--;
            if (i< 0)
                timer.cancel();
        }
    }, 0, 1000);

当我有System.out.println(i--);时,它在简单的Java应用程序中运行良好System.out.println(i--); 而不是tv2_r7.setText(String.valueOf(i)); i--; tv2_r7.setText(String.valueOf(i)); i--;

您已更新计时器中的UI值,这是错误的。 你需要使用

runOnUIThread

方法那里。

tv2_r7 = (TextView) this.findViewById(R.id.textView2_r7);

    final Timer timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask()
    {
        int i = 10;

        public void run()
        {
            runOnUIThread(new Runnable()
            {

                @Override
                public void run()
                {
                    tv2_r7.setText(String.valueOf(i));

                }
            });

            i--;
            if (i < 0)
                timer.cancel();
        }
    }, 0, 1000);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM