简体   繁体   English

我应该将 cityName 添加到具有 4 个片段的导航组件中的 Bundle 多少次?

[英]How many times should I add cityName to Bundle in Navigation Component with 4 fragments?

I have implemented Navigation Component with 4 fragments:我已经用 4 个片段实现了导航组件:

F1 -> F2 -> F3 -> F4

To navigate from F1 -> F2 , I use:要从F1 -> F2导航,我使用:

val bundle = bundleOf("cityName" to cityName)
findNavController().navigate(R.id.second_fragment, bundle)

Now, I want to propagate the "cityName" all the way to F4.现在,我想将“cityName”一直传播到 F4。 Is it necessary to do the same thing also when navigation from F2 -> F3 and F3 -> F4 , or is it enough to do it only once, as I already did?F2 -> F3F3 -> F4导航时是否也需要做同样的事情,还是像我已经做过的那样只做一次就足够了?

If you use arguments, you need to propagate them from one fragment to another, because each fragment can have different set of arguments.如果使用 arguments,则需要将它们从一个片段传播到另一个片段,因为每个片段可以有不同的 arguments 集。 You can improve this by using Safe Args plugin .您可以通过使用Safe Args 插件来改进这一点。

Alternative 1备选方案 1

In case of single activity it's easy to define shared view model to control common ui parts of your app (app bar title, for example)在单个活动的情况下,很容易定义共享视图 model来控制应用程序的常见 ui 部分(例如应用程序栏标题)

interface HostViewModel {
    
    val screenTitle: LiveData<String>

    fun setScreenTitle(title: String)
}

Alternative 2备选方案 2

You can create nested graph for your flow (F1->...->F4) and tie destination view model to it您可以为您的流程 (F1->...->F4) 创建嵌套图并将目标视图 model与它联系起来

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM