为什么Postdelayed不在if语句中工作 [英] Why Postdelayed is not working in the if statement

查看:219
本文介绍了为什么Postdelayed不在if语句中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在if语句中放置 postDelayed(this,1000); 时,为什么计时器停止工作,就在秒++;
布局中有3个按钮(开始,停止,重置)。按Start-> running = true,按stop-> running = stop,按reset-> running = false seconds = 0

Why does the timer stop working when i put the postDelayed(this,1000); inside the if statement, just under seconds++;? There are 3 buttons (start,stop,reset) in the layout. Press Start->running=true,press stop->running=stop,press reset->running=false seconds=0

private void runTimer() {

    final TextView timeView = (TextView) findViewById(R.id.time_view);
    final Handler handler = new Handler();

    handler.post(new Runnable() {

        @Override
        public void run() {
            int hours = seconds / 3600;
            int minutes = (seconds % 3600) / 60;
            int secs = seconds % 60;

            String time = String.format("%d:%2d:%02d", hours, minutes, secs);
            timeView.setText(time);
            if (running) {
                seconds++;
            //handler.postDelayed(this, 1000);
            //doesnt work if i put it here
            }
            handler.postDelayed(this, 1000);
        }
    });

}


推荐答案

你调用的时间 runTimer()变量运行设置为false。很可能你必须将 runTimer()的调用移到 onClickStart()方法中(在设置为run之后) )。$
当声明布尔值时,默认值为false。

At the time you call runTimer() the variable running is set to false. Most likely you have to move the call to runTimer() into the onClickStart() method (after setting running to true).
When declaring booleans their default value is assumed with false.

这篇关于为什么Postdelayed不在if语句中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆