Java 使用计时器计算秒数并更新活动中的字符串

Java 使用计时器计算秒数并更新活动中的字符串,java,android,timer,Java,Android,Timer,我试图在我的一个活动中创建一个计时器,它将每秒触发一次,增加seconds变量,然后在seconds==60时将分钟数增加1,在minutes==60时将小时数增加1 _currentSeconds = _level.GetTimeSpentSeconds(); _currentMinutes = _level.GetTimeSpentMinutes(); _currentHours = _level.GetTimeSpentHours(); String cu

我试图在我的一个活动中创建一个计时器,它将每秒触发一次,增加seconds变量,然后在seconds==60时将分钟数增加1,在minutes==60时将小时数增加1

    _currentSeconds = _level.GetTimeSpentSeconds();
    _currentMinutes = _level.GetTimeSpentMinutes();
    _currentHours = _level.GetTimeSpentHours();

    String currentTimeDisplay = _currentHours + "H " + _currentMinutes +"M " + _currentSeconds +"S";

    _txtCurrentTime = findViewById(R.id.txtCurrentTime);
    _txtCurrentTime.setText(currentTimeDisplay);

    _totalGameTime = new Timer();
    _totalGameTime.schedule(new TimerTick(), 1000);

}

private class TimerTick extends TimerTask{
    TextView _txtCurrentTime = findViewById(R.id.txtCurrentTime);
    public void run()   {
        _currentSeconds++;
        TextView _txtCurrentTime = findViewById(R.id.txtCurrentTime);
        if (_currentSeconds == 60){
            _currentSeconds = 0;
            _currentMinutes++;
        }

        if (_currentMinutes == 60){
            _currentMinutes = 0;
            _currentHours++;
        }

        String currentTimeDisplay = _currentHours + "H " + _currentMinutes +"M " + _currentSeconds +"S";
        _txtCurrentTime.setText(currentTimeDisplay);
        _level.SetTimeSpentSeconds(_currentSeconds);
        _level.SetTimeSpentMinutes(_currentMinutes);
        _level.SetTimeSpentHours(_currentHours);
    }
}

很难准确地说出程序是如何响应的,因为附加了调试器后,我的活动变得非常冗长,但这似乎没有起作用,TextView保持不变。

为此,您不需要使用TimerTask。您可以使用以下选项之一:

  • 您可以使用我为类似目的编写的此类- 您必须定义onTick()才能在每个“mCountUpInterval”时间间隔(在CountUpInterval类中定义)更新TextView

  • 用一个计时器。。。只需用XML或代码实现计时器,并使用其start()方法启动它,使用其stop()方法停止它。

    发现它正在崩溃,因为出于某种原因,我的文本视图的.setText在字节方面遇到了问题,并且必须将它们转换为带有Integer.toString(\u currentSeconds)的字符串。不知道为什么在计时器中这样做会导致这个问题