Navigation Architecture Component- Passing argument data to the startDestination

前端 未结 9 786
情话喂你
情话喂你 2020-12-05 16:43

I have an activity A that start activity B passing to it some intent data. Activity B host a navigation graph from the new Navigation Architecture Component.I want to pass t

9条回答
  •  执念已碎
    2020-12-05 17:28

    So finally, I have found a solution to this issue.

    At the time of writing this answer, I am using Navigation 2.2.0-alpha01

    If you want to pass some data to the start destination directly as arguments from host activity, you need to manually set your host’s navigation graph inside the host activity’s onCreate() method, as shown below:

    Get you navController:

    val navController by lazy { findNavController(R.id.) }
    

    Then in the host activity's onCreate()

    val bundle = Bundle()
    bundle.putString("some_argument", "some_value")
    navController.setGraph(R.navigation., bundle)
    

    Or if you want to pass the whole intent extras as it is to the startDestination:

    navController.setGraph(R.navigation., intent.extras)
    

    Since intent.extras would return a Bundle only

    When you are setting the navGraph using setGraph() method, you should avoid setting the app:NavGraph attribute in the NavHostFragment definition, because doing so results in inflating and setting the navigation graph twice.

    While reading these arguments in your startDestination fragment:

    If you are using the Safe Args Plugin (which is very much recommended), then in your fragment:

    private val args by navArgs()
    

    Safe Args plugin would generate an Args class by appending Args to your fragment name. For example, if you fragment is called DummyFragment then Safe Args would generate a class called DummyFragmentArgs

    where navArgs<> is an extension function defined in Android KTX

    If you are not using Android KTX, you can get the args object like:

    val args = DummyFragmentArgs.fromBundle(arguments!!)
    

    Once you've acquired the arguments object, you can simply fetch your arguments:

    args.someArgument
    

    Notice how we passed "some_argument" as argument, and we are reading it as someArgument using Safe Args

    If you are not using Safe Args (there is no reason to not use it though), you can access your arguments like this:

    arguments?.getString("some_argument")
    

    All of this is documented in Migrate to Navigation Component documentation here: https://developer.android.com/guide/navigation/navigation-migrate#pass_activity_destination_args_to_a_start_destination_fragment

提交回复
热议问题