我试图使用导航图将一个ArrayList<Profile>
从一个片段传递到另一个片段,但我得到了这个错误Type mismatch: inferred type is Array<Profile> but Array<(out) Parcelable!>? was expected
,我已经通过了导航我想要传递的参数类型。我错过了什么?这里是我的代码
emptyHomeViewModel.playerByIDLiveData.observe(viewLifecycleOwner) { profile ->
if (profile != null) {
profilesList.add(profile)
bundle = Bundle().apply {
putSerializable("user", profilesList)
}
findNavController().navigate(
R.id.action_emptyHomeFragment_to_selectUserFragment,
bundle
)
将接收
的片段的导航XML<fragment
android:id="@+id/selectUserFragment"
android:name="com.example.dota2statistics.SelectUserFragment"
android:label="fragment_select_user"
tools:layout="@layout/fragment_select_user" >
<argument
android:name="user"
app:argType="com.example.dota2statistics.data.models.byID.Profile[]" />
</fragment>
接收数组列表的片段的代码
class SelectUserFragment : Fragment(R.layout.fragment_select_user) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val args : SelectUserFragmentArgs by navArgs()
val profilesList = args.user
Log.i("Profiles", "onViewCreated: ${profilesList[0].personaname} ================")
}
添加插件
plugins {
id("kotlin-parcelize")
}
然后使你的类可打包,例如
import kotlinx.parcelize.Parcelize
@Parcelize
class User(val firstName: String, val lastName: String, val age: Int): Parcelable
安全参数只允许传递Array,所以在添加bundle之前我们必须将ArrayList转换为Array
bundle.putParcelableArray("user", profilesList.toTypedArray())
当获得参数时,我们可以将其转换回ArrayList
val list: ArrayList<Profile> = ArrayList(args.user.toList())