Navigation Component: pass safeArgs from activity to a fragment

北城余情 提交于 2020-11-27 05:05:51

问题


I have two graphs, so the first graph move from one fragment to an activity passing safeArgs to the activity.

val action = MyFragmentDirections.actionMyActivity(arg1, arg2)
Navigation.findNavController(view).navigate(action)  

Now in the second, I want to pass these arguments from MyActivity to a fragment which belongs to this activity.

I can get the args:

val args = MyActivity.fromBundle(intent.extras)

The problem is there is not a Directions file for this activity, so I can't pass the arguments.


回答1:


Navigation 1.0.0-alpha07 fixed the feature request for passing arguments to the start destination of a graph.

To use this, you'd need to:

  1. Remove the app:navGraph attribute from your NavHostFragment
  2. Call findNavController(R.id.your_nav_host_fragment).setGraph(R.navigation.your_graph, intent.extras)

Using the R.id of your NavHostFragment and R.navigation that you previously had on your app:navGraph tag. By passing the arguments into the setGraph call, your starting destination will get the arguments directly, without calling navigate again (which would, by default, create a new instance of the destination on your back stack - not what you want).




回答2:


I don't know if this is recommended, but it is working:

val args = MyActivity.fromBundle(intent.extras)
navController.navigate(R.id.myActivityFragment, args.toBundle())


来源:https://stackoverflow.com/questions/53731571/navigation-component-pass-safeargs-from-activity-to-a-fragment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!