Passing enum or object through an intent (the best solution)

前端 未结 15 1003
时光取名叫无心
时光取名叫无心 2020-12-04 05:41

I have an activity that when started needs access to two different ArrayLists. Both Lists are different Objects I have created myself.

Basically I need a way to pa

15条回答
  •  感动是毒
    2020-12-04 06:06

    Use Kotlin Extension Functions

    inline fun > Intent.putExtra(enumVal: T, key: String? = T::class.qualifiedName): Intent =
        putExtra(key, enumVal.ordinal)
    
    inline fun > Intent.getEnumExtra(key: String? = T::class.qualifiedName): T? =
        getIntExtra(key, -1)
            .takeUnless { it == -1 }
            ?.let { T::class.java.enumConstants[it] }
    

    This gives you the flexibility to pass multiple of the same enum type, or default to using the class name.

    // Add to gradle
    implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
    
    // Import the extension functions
    import path.to.my.kotlin.script.putExtra
    import path.to.my.kotlin.script.getEnumExtra
    
    // To Send
    intent.putExtra(MyEnumClass.VALUE)
    
    // To Receive
    val result = intent.getEnumExtra()
    

提交回复
热议问题