简体   繁体   中英

Using variable from another file Kotlin

if I have 2 Activities and I want to add if condition from a variable on the another activity How can I do that? like if i have the variable that contains 9 numbers in the first layout(first activity) and i want to set if condition in the another one using the x variable that is the question. I am using Android Studio with kotlin.

If the value of your variable doesn't change after you start your second activity, you can use extras to pass the value between them.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM