带 ProgressBar 的 CountDownTimer,重启应用时继续进度条

Posted

技术标签:

【中文标题】带 ProgressBar 的 CountDownTimer,重启应用时继续进度条【英文标题】:CountDownTimer with ProgressBar, continuing progressbar when restarting the app 【发布时间】:2022-01-09 22:32:13 【问题描述】:

我有一个显示 CountdownTimer 进度的 ProgressBar。 ProgressBar 工作除了当我关闭应用程序并重新启动它。如果我这样做,ProgressBar 从零开始。它不会从我离开的地方继续。

我有一个变量来保持以毫秒为单位的倒计时。我设法通过在 OnStop 和 OnStart 方法中使用 SharedPreferences 来正确维护它。但是如何正确使用这个变量来维护 ProgressBar 的进度呢?

private fun startCountdown() 

    var i = 1

    object : CountDownTimer(timeLeftInMilliseconds, 1000) 

        override fun onTick(millisUntilFinished: Long) 

            timeLeftInMilliseconds = millisUntilFinished
            
            i++

            myProgressBar.progress = (i * 100 / (40000 / 1000)).toInt()
            //Instead of 40000 here, I have tried to use the variable 
            //timeLeftInMilliSeconds or millisUntilFinished, but that doesn't work. 
        

        override fun onFinish() 
            progressBarOutOfLikesTimer.progress = 100;
            timeLeftInMilliseconds = 40000
        

【问题讨论】:

显示更多代码,例如您提到的 onStart 和 onStop 函数。我的猜测是你的 onStop 方法没有被调用。 【参考方案1】:

我认为这个i 变量增加了不必要的复杂性。您可以根据剩余时间除以总时间直接计算要填充的条形的分数。我在这里使用toDouble() 来确保我们没有进行整数数学运算并得到不必要的截断。我假设 ProgressBar 的 max 是 100。您应该将时间分数乘以 max 的任何值。

private fun startCountdown() 

    object : CountDownTimer(timeLeftInMilliseconds, 1000) 

        override fun onTick(millisUntilFinished: Long) 
            timeLeftInMilliseconds = millisUntilFinished
            myProgressBar.progress = (100 * (1.0 - millisUntilFinished.toDouble() / 40000)).toInt()
        

        override fun onFinish() 
            progressBarOutOfLikesTimer.progress = 100;
            timeLeftInMilliseconds = 40000
        

【讨论】:

所以它现在原则上可以工作,但是我该如何反转它以便 ProgressBar 慢慢填充?在您的示例中,它以完整的 ProgressBar 开始,然后逆时针缓慢“清空”自身。我希望它顺时针填充。 哦,对了。只需从 1 中减去分数即可将其反转。我在上面更新了它。 不是这样,现在根本不显示任何进度。 您确定完全复制了吗?我用这段代码做了一个示例项目,它工作正常。 我的错。你说得对。我在错误的地方有一个括号.. geez.

以上是关于带 ProgressBar 的 CountDownTimer,重启应用时继续进度条的主要内容,如果未能解决你的问题,请参考以下文章

JavaFX:带时间轴的ProgressBar;如果完成则重置两者

android 自定义progressbar怎么让右侧也是圆角

Android自定义文本的进度条

vue-countdown组件

ext xtype

countdown