gpt4 book ai didi

Android Kotlin : putParcelableArrayList(ArrayList) and getParcelableArrayList() wont work

转载 作者:行者123 更新时间:2023-12-02 10:08:21 27 4
gpt4 key购买 nike

我正在尝试通过ArrayList<Integer>从 fragment 到另一个 fragment ,这是我的代码:

Kotlin 代码

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
}
}

但它说:

Type mismatch.

Required: java.util.ArrayList !

Found: kotlin.collections.ArrayList /* = java.util.ArrayList */

当我尝试阅读它时,也是同样的情况。

Kotlin 代码

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

它说:

Type argument is not within its bounds

Expected: Parcelable!

Found: Int

我已经用 Java 对其进行了测试并且工作正常。

最佳答案

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

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)
}
}
}

然后使用这个类在Fragment之间或者(Activty到Fragment)之间传递数据

例如,将列表从 fragment 传递到 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
}
}

获取列表:

val any = arguments?.getParcelable<BaseParcelable>(Constant.BRANDS_LIST).value
val list = any as ArrayList<Int>

关于Android Kotlin : putParcelableArrayList(ArrayList<int>) and getParcelableArrayList<Int>() wont work,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51331659/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com