How to send an object from one Android Activity to another using Intents?

后端 未结 30 3700
-上瘾入骨i
-上瘾入骨i 2020-11-21 04:47

How can I pass an object of a custom type from one Activity to another using the putExtra() method of the class Intent?

30条回答
  •  再見小時候
    2020-11-21 05:22

    In Koltin

    Add kotlin extension in your build.gradle.

    apply plugin: 'kotlin-android-extensions'
    
    android {
        androidExtensions {
            experimental = true
       }
    }
    

    Then create your data class like this.

    @Parcelize
    data class Sample(val id: Int, val name: String) : Parcelable
    

    Pass Object with Intent

    val sample = Sample(1,"naveen")
    
    val intent = Intent(context, YourActivity::class.java)
        intent.putExtra("id", sample)
        startActivity(intent)
    

    Get object with intent

    val sample = intent.getParcelableExtra("id")
    

提交回复
热议问题