-4
在kotlin中創建parcelable對象的最佳方法是什麼?在kotlin中創建一個parcelable對象
在kotlin中創建parcelable對象的最佳方法是什麼?在kotlin中創建一個parcelable對象
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)
}
}
}
走在這條鏈接,全面的解決方案
*這*就是Android的方式來傳遞對象。應該被標記爲接受的答案。 –
@ Miha_x64 yaaa,但你可以在kotlin中做到這一點 – Sendy
哦,我從來沒有注意到它是用Java編寫的。在Kotlin和Java之間切換對我來說絕對是無縫的。 :) –