Kotlin/Android Studio-如何将变量从替代乐趣传递到应用程序的其余部分? [英] Kotlin / Android Studio - How can I pass a variable from an override fun to the rest of the app?

查看:83
本文介绍了Kotlin/Android Studio-如何将变量从替代乐趣传递到应用程序的其余部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我四处张望,没有找到解决我问题的好方法.在我的应用程序上,我有一个计时器.该计时器在点击时停止,我想根据剩余时间计算得分.我可以使用"millisUntilFinished"来计算分数,但是无法在我的应用中重用score变量.您能以正确/最佳的方式帮助我吗?下面是我的代码:

I have looked around a bit, and have found no good answer to my problem. On my app, I've got a timer. This timer stops on a click, and I would like to calculate a score based on the time left. I can use the "millisUntilFinished" to calculate the score, but I can't reused the score variable in my app. Could you please help me with the correct / best way to do this ? Below, my code:

var score: Long

        val timer = object : CountDownTimer(20000, 1000) {
        override fun onTick(millisUntilFinished: Long)  {
            timer.setText("" + millisUntilFinished / 1000)
              score = millisUntilFinished / 1000
            }
            override fun onFinish() {
            timer.setText("0");
        }
    }
    timer.start()

稍后当我尝试在应用程序中使用它时,我得到一个"变量'score'必须被初始化."我已经尝试了很多东西,但是每次我最终都没有能够重用在替代功能中初始化的变量.

When I try to use it later in my app, I get a "Variable 'score' must be initialized." I've tried quite a few things but every time I end up not being able to reuse a variable initialized in an override fun.

感谢您的帮助!

推荐答案

您可以将其定义为lateinit var或应该对其进行初始化.

You may define it as lateinit var or you should initialize it.

lateinit var score: Long

        val timer = object : CountDownTimer(20000, 1000) {
        override fun onTick(millisUntilFinished: Long)  {
            timer.setText("" + millisUntilFinished / 1000)
              score = millisUntilFinished / 1000
            }
            override fun onFinish() {
            timer.setText("0");
        }
    }
    timer.start()

请注意,lateinit是在类中定义的,而不是在函数中定义的. 或者,您可以使用以下方法:

Note that lateinit defines in class not in function. Or you can use this:

var score=0.toLong()

        val timer = object : CountDownTimer(20000, 1000) {
        override fun onTick(millisUntilFinished: Long)  {
            timer.setText("" + millisUntilFinished / 1000)
              score = millisUntilFinished / 1000
            }
            override fun onFinish() {
            timer.setText("0");
        }
    }
    timer.start()

这篇关于Kotlin/Android Studio-如何将变量从替代乐趣传递到应用程序的其余部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆