package

androidx.navigation.fragment

Overview

The NavHostFragment provides a NavHost suitable for using Fragments as destinations in your navigation graphs via <fragment> elements. Navigating to a Fragment will replace the contents of the NavHostFragment.

Below is a minimal implementation.

 // File: res/xml/main_navigation.xml
 <navigation xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:app="http://schemas.android.com/apk/res-auto"
     app:startDestination="@+id/home_fragment">
   <fragment android:id="@+id/home_fragment"
       android:name="com.example.HomeFragment">
     <action android:id="@+id/details"
       app:destination="@+id/details_fragment" />
   </fragment>
   <fragment android:id="@+id/details_fragment"
       android:name="com.example.DetailsFragment"/>
 <navigation />

 // File: activity_main.xml
 <fragment
   android:id="@+id/my_nav_host_fragment"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:name="androidx.navigation.fragment.NavHostFragment"
   app:navGraph="@xml/main_navigation"
   app:defaultNavHost="true"
 />

 // File: HomeFragment.java
 public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
   // For example purposes, assume our layout created in onCreateView has a Button
   // that should navigate the user to a destination
   Button button = view.findViewById(R.id.view_details);

   // Retrieve the NavController from any Fragment created by a NavHostFragment by passing in
   // this
   final NavController navController = NavHostFragment.findNavController(this);
   // Alternatively, retrieve the NavController from any View within the NavHostFragment
   final NavController viewNavController = Navigation.findNavController(button);

   // And set the listener
   button.setOnClickListener(() -> navController.navigate(R.id.details));

   // Or use the convenience method in Navigation to combine all of the previous steps
   button.setOnClickListener(Navigation.createNavigateOnClickListener(R.id.details));
 }
 

Classes

DialogFragmentNavigatorNavigator that uses DialogFragment.show(FragmentManager, String).
DialogFragmentNavigator.DestinationNavDestination specific to DialogFragmentNavigator.
FragmentNavigatorNavigator that navigates through fragment transactions.
FragmentNavigator.DestinationNavDestination specific to FragmentNavigator
FragmentNavigator.ExtrasExtras that can be passed to FragmentNavigator to enable Fragment specific behavior
FragmentNavigator.Extras.BuilderBuilder for constructing new FragmentNavigator.Extras instances.
NavHostFragmentNavHostFragment provides an area within your layout for self-contained navigation to occur.