【问题标题】:Cannot see Countdown Timer Android看不到倒数计时器 Android
【发布时间】:2021-12-03 08:24:06
【问题描述】:

已编辑:现在,我知道为什么了。这是因为我没有正确地在片段上调用它。现在正在运行!

它运行没有错误,但不起作用。 我希望在我在 XML 上创建的文本视图中看到计时器,但它没有显示任何内容。

这是我的 ViewModel 文件

class TotpViewModel: ViewModel() {

private var _time = MutableLiveData<String>()
val time : LiveData<String>
    get() = _time

private var mTimer = Timer()

init {
    startTimer()
 }

private fun startTimer() {
    var remainTime : Int = 1800
    mTimer = timer(period = 1000) {
        remainTime--
        _time.postValue("Time : " +
                (remainTime / 60.0).toInt().toString().padStart(2,'0') + ":" +
                (remainTime % 60).toInt().toString().padStart(2,'0'))

        if(remainTime == 0) stopTimer()
    }
}

fun stopTimer() {
    mTimer.cancel()
}


fun onBackPress() {
}

}

任何帮助将不胜感激。谢谢

【问题讨论】:

  • 看来你错过了binding.viewModel = viewModel
  • 虽然我声明了“viewModel = ViewModelProvider(this,).get(TotpViewModel::class.java)”,但我还需要它吗?当我写那行时发生错误...
  • 您还需要将此视图模型发送到 xml。 bidning.totpviewModel = viewModel

标签: android kotlin countdown countdowntimer


【解决方案1】:

这是因为您在onViewCreated 中调用viewModel.stopTimer() 取消计时器并在显示视图时停止它

【讨论】:

  • 我应该在哪里调用它?进行了多次试验来更改调用它的位置,但我无法做到
  • @Lucy 我的问题是你为什么要手动取消你的计时器?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多