lightbulb_outline Help shape the future of the Google Play Console, Android Studio, and Firebase. Start survey

androidx.navigation.fragment

The androidx.navigation.fragment.NavHostFragment provides a androidx.navigation.NavHost suitable for using Fragments as destinations in your navigation graphs via <fragment%gt; 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(() -%gt; 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

FragmentNavigator

Navigator that navigates through FragmentTransaction.

FragmentNavigatorDestinationBuilder

DSL for constructing a new FragmentNavigator.Destination

NavHostFragment

NavHostFragment provides an area within your layout for self-contained navigation to occur.

Extension functions summary

Extension functions

findNavController

fun Fragment.findNavController(): NavController

Find a NavController given a Fragment

Calling this on a Fragment that is not a NavHostFragment or within a NavHostFragment will result in an IllegalStateException

fragment

inline fun <reified F : Fragment> NavGraphBuilder.fragment(id: Int): Unit

Construct a new FragmentNavigator.Destination

fragment

inline fun <reified F : Fragment> NavGraphBuilder.fragment(id: Int, block: FragmentNavigatorDestinationBuilder.() -> Unit): Unit

Construct a new FragmentNavigator.Destination