Android kotlin: putParcelableArrayList(ArrayList<int>) 和 getParcelableArrayList<Int>() 不起作用

Moh*_*Ali 4 android arraylist parcelable kotlin

我试图ArrayList<Integer>从片段传递到另一个片段,这是我的代码:

科特林代码

companion object {
    fun newInstance(categoryId: Int, brandsList: ArrayList<Int>): Fragment {
        val fragment = CategoryAllAdsFragment()
        fragment.arguments = Bundle()
        fragment.arguments!!.putInt(Constant.CATEGORY_ID, categoryId)
        fragment.arguments!!.putParcelableArrayList(Constant.BRANDS_LIST, brandsList)
        return fragment
    }
}
Run Code Online (Sandbox Code Playgroud)

但它说:

类型不匹配。

必需: java.util.ArrayList !

发现:kotlin.collections.ArrayList /* = java.util.ArrayList */

当我试图阅读它时,也是同样的事情。

科特林代码

try {
    val brandsList = arguments!!.getParcelableArrayList<Int>(Constant.BRANDS_LIST)
} catch (ex: Exception) {
    throw Exception("brand list cannot be null")
}
Run Code Online (Sandbox Code Playgroud)

它说:

类型参数不在其范围内

预期:可打包!

发现:Int

我已经测试过它Java并且它工作正常。

Mon*_*aih 8

您可以创建一个包含类型变量的通用 Parcelable 类 (Any)

class BaseParcelable : Parcelable {

    var value: Any

    constructor(value: Any) {
        this.value = value
    }

    constructor(parcel: Parcel) {
        this.value = Any()
    }

    override fun writeToParcel(dest: Parcel?, flags: Int) {}

    override fun describeContents(): Int = 0

    companion object CREATOR : Parcelable.Creator<BaseParcelable> {

        override fun createFromParcel(parcel: Parcel): BaseParcelable {
            return BaseParcelable(parcel)
        }

        override fun newArray(size: Int): Array<BaseParcelable?> {
            return arrayOfNulls(size)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后使用这个类在片段之间或(Activty to Fragment)之间传递数据

将列表从片段传递到片段,例如:

companion object {
    fun newInstance(categoryId: Int, brandsList: ArrayList<Int>): Fragment {
       val fragment = CategoryAllAdsFragment()
       fragment.arguments = Bundle()
       fragment.arguments!!.putInt(Constant.CATEGORY_ID, categoryId)
       fragment.arguments!!.putParcelable(Constant.BRANDS_LIST, BaseParcelable(brandsList))
       return fragment
    }
}
Run Code Online (Sandbox Code Playgroud)

要获取列表:

val any = arguments?.getParcelable<BaseParcelable>(Constant.BRANDS_LIST).value
val list = any as ArrayList<Int>
Run Code Online (Sandbox Code Playgroud)


Abn*_*cio 6

使用

  • putIntegerArrayList(字符串键,ArrayList值)

  • 将 ArrayList 值插入到此 Bundle 的映射中,替换给定键的任何现有值

putIntegerArrayList(Constant.BRANDS_LIST, array)
Run Code Online (Sandbox Code Playgroud)

并变得像

  • getIntegerArrayList(字符串键)

  • 返回与给定键关联的值;如果给定键不存在所需类型的映射,或者 null 值与该键显式关联,则返回 null。

extras.getIntegerArrayList(Constant.BRANDS_LIST)
Run Code Online (Sandbox Code Playgroud)