XML 代码中不设置grap
<FrameLayout
android:id="@+id/frameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="@+id/main_nav_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true" />
</FrameLayout>
navigation grap 布局 nav_activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/nav_activity_main"
app:startDestination="@id/newsFragment"
tools:ignore="UnusedNavigation">
<fragment
android:id="@+id/newsFragment"
android:name="com.wtf.sample.ui.NewsFragment"
android:label="NewsFragment">
<argument
android:name="username"
app:argType="string" />
</fragment>
</navigation>
MainActivity中
var name = "harveyhaha"
val args = NewsFragmentArgs(name)
Navigation.findNavController(this, R.id.main_nav_fragment)
.setGraph(R.navigation.nav_activity_main, args.toBundle())
NewsFragment接收
class NewsFragment : Fragment(){
val args: NewsFragmentArgs by navArgs()
}