全局访问CountDownTimer变量

德罗牛

我只是从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代码块内。

Ambareesh B
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()

这应该是全局的(在“活动”的所有方法之后都应位于底部)

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"
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章