You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android导航组件中如何传递嵌套列表(列表的列表)?

传递嵌套列表到Fragment的几种方案

方案一:用Parcelable封装嵌套列表

Navigation组件支持传递Parcelable类型参数,你可以把嵌套列表封装到自定义Parcelable类中:

  1. 创建Parcelable类
import android.os.Parcelable
import kotlinx.parcelize.Parcelize

@Parcelize
data class NestedStringList(val list: List<List<String>>) : Parcelable

(注意需要在项目的build.gradle中添加kotlin-parcelize插件依赖)

  1. 在navigation.xml中配置参数
<argument
    android:name="nested_list"
    app:argType="com.yourpackage.NestedStringList" />
  1. 发起导航时传递参数
val action = YourCurrentFragmentDirections.actionToTargetFragment(
    NestedStringList(asd)
)
findNavController().navigate(action)
  1. 在目标Fragment接收参数
val nestedList = arguments?.getParcelable<NestedStringList>("nested_list")?.list

方案二:序列化字符串传递

将嵌套列表转换为JSON字符串传递,在目标Fragment再解析回原结构(以Gson为例):

  1. 导航前序列化嵌套列表
val gson = Gson()
val nestedListStr = gson.toJson(asd)
val action = YourCurrentFragmentDirections.actionToTargetFragment(nestedListStr)
findNavController().navigate(action)
  1. 在navigation.xml中配置字符串类型参数
<argument
    android:name="nested_list_str"
    app:argType="string" />
  1. 目标Fragment解析字符串
val nestedListStr = arguments?.getString("nested_list_str")
val type = object : TypeToken<List<List<String>>>() {}.type
val nestedList = Gson().fromJson<List<List<String>>>(nestedListStr, type)

方案三:用ViewModel共享数据

如果两个Fragment属于同一个Activity,直接通过ViewModel共享数据更高效,无需通过Navigation参数传递:

  1. 创建共享ViewModel
class SharedViewModel : ViewModel() {
    val nestedList = MutableLiveData<List<List<String>>>()
}
  1. 当前Fragment设置数据
val viewModel = ViewModelProvider(requireActivity())[SharedViewModel::class.java]
viewModel.nestedList.value = asd
  1. 目标Fragment获取数据
val viewModel = ViewModelProvider(requireActivity())[SharedViewModel::class.java]
viewModel.nestedList.observe(viewLifecycleOwner) { list ->
    // 处理嵌套列表数据
}

内容的提问来源于stack exchange,提问作者HaveMercyOnMe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 01:36:20