【问题标题】:creating a parcelable object in kotlin在 kotlin 中创建一个可打包的对象
【发布时间】:2017-06-05 05:14:32
【问题描述】:

在 kotlin 中创建 Parcelable 对象的最佳方法是什么?

【问题讨论】:

    标签: android android-intent kotlin parcelable


    【解决方案1】:

    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

    【讨论】:

    • @Miha_x64 yaaa 但你可以在 kotlin 中做到这一点
    • 哦,我从来没有注意到它是在 Java 中的。在 Kotlin 和 Java 之间切换对我来说绝对是无缝的。 :)
    • @Miha_x64 plzzz 解决这个问题stackoverflow.com/questions/44361960/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多