【问题标题】:Using variable from another file Kotlin使用来自另一个文件 Kotlin 的变量
【发布时间】:2017-06-09 22:10:25
【问题描述】:

如果我有 2 个活动,并且我想从另一个活动的变量中添加 if 条件,我该怎么做? 就像我在第一个布局(第一个活动)中有包含 9 个数字的变量,并且我想使用问题的 x 变量在另一个布局中设置 if 条件。 我正在使用带有 kotlin 的 Android Studio。

【问题讨论】:

  • 好吧,从其他活动中获取变量通常是个坏主意,因为其他活动可能会同时被破坏。如果您有想要跨活动共享的变量,请在 Application 类中声明它并通过 (YourApplicationClass)getApplicationContext() 获取它们。
  • 谢谢!成功了!

标签: android android-layout android-studio kotlin


【解决方案1】:

如果您的变量的值在您开始第二个活动后没有改变,您可以使用 extras 在它们之间传递值。

class FirstActivity : Activity() {

    var myVariable: Boolean = false

    fun gotoSecondActivity() {
        val intent = Intent(this, SecondActivity::class.java)
        intent.putExtra("MyVariable", myVariable)
        startActivity(intent)
    }
}

class SecondActivity: Activity() {
    fun getMyVariable(): Boolean {
        if (intent != null) {
            if (intent.extras != null) {
                return intent.extras.getBoolean("MyVariable")
            }
        }
        return false // default
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-29
    • 2021-03-28
    • 1970-01-01
    • 2019-06-27
    • 1970-01-01
    • 2022-12-18
    相关资源
    最近更新 更多