When using Navigation, the Fragment jump needs to pass parameters.

Pass parameters between Fragment jumps.

Navigate for fragments with navController. navigate(@idres int resId, @Nullable Bundle args)

How to pass the first Fragment of an Activity

When using Navigation, use < Navigation >… will have a specified Fragment. This Fragment is usually through androidx. Fragments. App. FragmentContainerView fill, then the default will start specified fragments.

So how do you pass data to this Fragment?

First, we need to set up the data in the dependent Activity (we pass the data through the Bundle).

private fun setupNavigation(data: Bundle) {
    val fragment = supportFragmentManager.findFragmentById(R.id.nav_xxx) as NavHostFragment
    val controller = fragment.navController
    val navigation = controller.graph
    val navArgument = NavArgument.Builder()
            .setDefaultValue(data)
            .build()
    navigation.addArgument("bundle", navArgument)
}
Copy the code

Second, fetch data in fragments

val argument = NavHostFragment.findNavController(this).graph.arguments["bundle"] argument? .let { val value = it.defaultValue as Bundle xxx = value.getString(xxx) yyy = value.getString(yyy) }Copy the code

Note:

  • To get the NavController, use the NavHostFragment method above and pass the data in Oncreate
  • Use Navigation. FindNavController (this, viewId) get NavController in onCreate may be an error, need to be in the post processing (), because in this way in the onCreate () method to obtain, NavController has not been generated yet. An exception is thrown.
  • In passing parameters, the first Fragment must be created. If we can’t use this method when we probably won’t need the home page Fragment, we can either use getActivity to get parameters or use EventBus to send Sticky messages.