全局访问 CountDownTimer 变量

Accessing CountDownTimer variable globally

我刚开始使用 Kotlin 来制作 Android 应用程序(这是我的第一门编程语言)并且我正在使用 CountDownTimer。我想全局访问 p0 参数,但我不知道如何访问。这是代码:

class MainActivity : AppCompatActivity() { 

    var score: Int = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

      var timeTimer = object : CountDownTimer(10000, 1000) {
          override fun onFinish() {
              timeView.text = "Time's up!"
          }

          override fun onTick(p0: Long) {
              timeView.text = "Time's left: " + p0/1000
          }
      }.start()
    }

    fun point (view: View) {
        score++
        p0 = p0 + 1000
        scoreView.text = "Score: $score"
    }
}

点击按钮调用功能点。我想要实现的是每次用户单击按钮时使 CountDownTimer 延长 1 秒。

这一行 p0 = p0 + 1000 显然行不通,因为 p0 在另一个代码块中。有什么办法可以让它在全球范围内访问吗?我考虑过将 CountDownTimer 放在 onCreate 之外并在 onCreate 中启动它,但我认为它仍然行不通,因为 p0 仍在 CountDownTimer 代码块内。

我不知道您的应用的覆盖范围,但您可以做几件事:

  • 为您的应用程序创建自定义应用程序 class 并检查那里的变量。您需要创建一个从 Application 扩展的 class 并将 class 添加到您的清单中,在 android:name 属性下的 <application/> 标记中。您可以像单例一样从任何地方访问您的自定义应用程序 class,例如 MyApp.getInstance().setPvalue(someIntValue).

  • 也许您想将该值保存在您的 SharedPreferences 中,以便在您关闭应用程序时它会一直保存。

  • 也许您想在服务中拥有该值,因此如果您关闭应用程序,计时器仍会倒计时。

前几天我回答了一个非常相似的问题:

希望对您有所帮助。

var timeTimer = object : CountDownTimer(10000, 1000) {
      override fun onFinish() {
          timeView.text = "Time's up!"
      }

      override fun onTick(p0: Long) {
          timeLeft = p0  //timeLeft is global --only way I think to keep track remaining time.
          timeView.text = "Time's left: " + p0/1000
      }
  }.start()

这应该是全局的(在 Activity 的所有方法之后在底部更好)

fun resetTimer(time){
   timeTimer.cancel()
   timeTimer = object : CountDownTimer(time, 1000) {
      override fun onFinish() {
          timeView.text = "Time's up!"
      }

      override fun onTick(p0: Long) {
          timeLeft = p0  
          timeView.text = "Time's left: " + p0/1000
      }
  }.start()

}

所以终于

fun point (view: View) {
    score++
    resetTimer(timeLeft + 1000)
    scoreView.text = "Score: $score"
}