【问题标题】:How to Pass Generic List of Any Type Through NavComp Fragment Args如何通过 NavComp 片段参数传递任何类型的通用列表
【发布时间】:2022-01-01 14:55:02
【问题描述】:

我正在将项目从许多活动转换为一个包含许多片段的活动,并使用导航组件来做到这一点。有一个活动接受多个列表,其中包含所有不同类型的大约 10 个不同列表。在创建要传递给片段的参数时,如何为可以是任何类型列表的 arg 执行此操作?

这是我从 onCreate 中的活动中获取它的方法。

intent.getParcelableArrayListExtra<Parcelable>("listItems")

我知道当我将它发送到片段时我将不得不做这样的事情

val bundle = bundleOf("ListItems" to (list as ArrayList<out Parcelable>))
findNavController().navigate(R.id.action, bundle)
          

【问题讨论】:

    标签: android android-fragments android-architecture-navigation android-navigation


    【解决方案1】:

    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)
    

    您可以使用savedStateHandlebundle 在目标片段中接收此信息

    使用bundle

    val args: DestinationFragmentArgs by navArgs()
    
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        val passesDataArray = args.test //here is your array of custom parcelable
    }
    

    【讨论】:

    • 为什么 argType 不能是 java.util.ArrayList,愚蠢的导航没有想到我们可能想将列表传递给片段......愚蠢的谷歌。我只是在使用 navcomp 时通过 -- bundleOf(LISTITEMS to (list as java.util.ArrayList) 将它传递给片段然后只使用 arguments?.getParcelableArrayList(LISTITEMS)
    【解决方案2】:
    class AlbumFileList : ArrayList<String>()
    

    试试这个

    【讨论】:

      猜你喜欢
      • 2020-11-03
      • 1970-01-01
      • 1970-01-01
      • 2019-11-11
      • 1970-01-01
      • 1970-01-01
      • 2018-05-25
      • 1970-01-01
      • 2021-04-24
      相关资源
      最近更新 更多