2017-06-05 116 views

回答

5

TestActivity.kt

class TestActivity : Activity() { 
    val DEVOTIONAL_RESPONSE: String = "DEVOTIONAL_RESPONSE" 
    var holdr: Holdr_ActivityTest? = null 

    override fun onCreate(savedInstanceState: Bundle?) { 
     super.onCreate(savedInstanceState) 
     setContentView(R.layout.activity_test) 
     holdr = Holdr_ActivityTest(findViewById(android.R.id.content)) 

     //create response 
     var response: DevotionalResponse = DevotionalResponse() 
     fillInResponse(response) 

     //write it to a Bundle 
     var newBundle: Bundle = Bundle() 
     newBundle.putParcelable(DEVOTIONAL_RESPONSE, response) 

     //read it from the new Bundle 
     var newResponse: DevotionalResponse = newBundle.getParcelable(DEVOTIONAL_RESPONSE) 

     //check that they're the same 
     assert(newResponse.getDevotionals().get(0).getContent().equalsIgnoreCase(response.getDevotionals().get(0).getContent())) 
    } 
} 

DevotionalResponse.kt

class DevotionalResponse() : Parcelable { 

    @Expose 
    var devotionals = arrayListOf<Devotional>(); 

    constructor(in: Parcel) : this() { 
     in.readTypedList(this.devotionals, Devotional.CREATOR) 
    } 

    override fun describeContents(): Int = 0 

    override fun writeToParcel(dest: Parcel, flags: Int) { 
     dest.writeTypedList(devotionals) 
    } 

    companion object { 
     @JvmField val CREATOR = object : Parcelable.Creator<DevotionalResponse>() { 
      override fun createFromParcel(in: Parcel): DevotionalResponse = 
        DevotionalResponse(in) 

      override fun newArray(size: Int): Array<DevotionalResponse?> = 
        arrayOfNulls(size) 
     } 
    } 
} 

走在這條鏈接,全面的解決方案

Kotlin Object Example

+0

*這*就是Android的方式來傳遞對象。應該被標記爲接受的答案。 –

+0

@ Miha_x64 yaaa,但你可以在kotlin中做到這一點 – Sendy

+0

哦,我從來沒有注意到它是用Java編寫的。在Kotlin和Java之間切換對我來說絕對是無縫的。 :) –