[英]How to Pass Generic List of Any Type Through NavComp Fragment Args
我正在将项目从许多活动转换为一个包含许多片段的活动,并使用导航组件来执行此操作。 有一项活动接受大约 10 个所有不同类型的不同列表的多个列表。 在为片段创建 arguments 以传递给它时,我该如何为可以是任何类型列表的 arg 执行此操作?
以下是我如何从 onCreate 中的活动中获取它。
intent.getParcelableArrayListExtra<Parcelable>("listItems")
我知道当我将它发送到片段时我将不得不做这样的事情
val bundle = bundleOf("ListItems" to (list as ArrayList<out Parcelable>))
findNavController().navigate(R.id.action, bundle)
safeArgs
仅支持自定义parcelable
和自定义parcelable
数组。
我们不能使用导航组件传递泛型列表,但我们可以传递一个parcelable
数组,我们可以使用toTypedArray()
将泛型列表转换为数组
在导航图中,将参数类型更改为目标片段中的自定义parceable
array
<fragment
android:id="@+id/destinationFragment"
android:name="com.example.destinationFragments"
android:label="destinationFragment"
tools:layout="@layout/fragment_destination" >
<argument
android:name="test"
app:argType="com.example.data.Test[]" />
</fragment>
现在,您可以发送通用列表,将其转换为TypedArray
val action = HomeFragmentDirections.actionHomeFragmentToDestinationFragment(list.toTypedArray())
findNavController().navigate(action)
您可以使用savedStateHandle
或bundle
在目标片段中接收它
使用bundle
val args: DestinationFragmentArgs by navArgs()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val passesDataArray = args.test //here is your array of custom parcelable
}
所以我最终这样做了。 对我来说它有点老套,但只要列表不是很大,它就会始终如一地工作。
binding.button.setOnClickListener {
val bundle = bundleOf("ListItems" to (list as ArrayList<out Parcelable>))
findNavController().navigate(R.id.action_home_to_see_list, bundle)
}
然后在片段中我将这些数据传递给我只是这样做
val list = arguments?.getParcelableArrayList<ListItems>("ListItems")?.toList()
对这个解决方案不满意,因为我觉得它很老套,但它确实有效
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.