Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

android - Navigation Architecture Component- Passing argument data to the startDestination

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 that intent data to the startDestination fragment as argument how to do that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

TLDR: You have to manually inflate the graph, add the keys/values to the defaultArgs, and set the graph on the navController.

Step 1

The documentation tells you to set the graph in the <fragment> tag in your Activity's layout. Something like:

<fragment
    android:id="@+id/navFragment"
    android:name="androidx.navigation.fragment.NavHostFragment"
    app:graph="@navigation/nav_whatever"
    app:defaultNavHost="true"
    />

REMOVE the line setting the graph=.

Step 2

In the Activity that will be displaying your NavHostFragment, inflate the graph like so:

val navHostFragment = navFragment as NavHostFragment
val inflater = navHostFragment.navController.navInflater
val graph = inflater.inflate(R.navigation.nav_whatever)

Where navFragment is the id you gave your fragment in XML, as above.

Step 3 [Crucial!]

Create a bundle to hold the arguments you want to pass to your startDestination fragment and add it to the graph's default arguments:

val bundle = Bundle()
// ...add keys and values
graph.addDefaultArguments(bundle)

Step 4

Set the graph on the host's navController:

navHostFragment.navController.graph = graph

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...