Introduction
NavHost and NavController help your app move between screens smoothly. They keep track of where you are and where you want to go.
NavHost and NavController help your app move between screens smoothly. They keep track of where you are and where you want to go.
val navController = findNavController(R.id.nav_host_fragment) // To navigate to a destination navController.navigate(R.id.destinationFragment)
val navController = findNavController(R.id.nav_host_fragment) navController.navigate(R.id.profileFragment)
navController.popBackStack()
val action = HomeFragmentDirections.actionHomeToDetails(itemId) navController.navigate(action)
This app has a button on the first screen. When you tap it, the app moves to the second screen using NavController.
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val navController = findNavController(R.id.nav_host_fragment) // Navigate to second screen when button clicked val button = findViewById<Button>(R.id.button_navigate) button.setOnClickListener { navController.navigate(R.id.secondFragment) } } }
Always define your navigation graph XML to list all screens and actions.
Use safe args plugin to pass data safely between screens.
NavController handles the back button automatically, so you don't need extra code.
NavHost shows your app screens inside one container.
NavController moves you between screens and manages back stack.
Use navigation graph XML to organize your app's navigation paths.
NavHost in Android navigation?NavController inside a Fragment?findNavController() extension function.findNavController().navigate(R.id.action_home_to_detail)
navigate() method moves the app to the destination defined by the action ID.R.id.action_home_to_detail is an action from Home to Detail screen in navigation graph.val navController = NavController() navController.navigate(R.id.action_main_to_settings)
findNavController(), not by calling constructor.Pass the test and this pattern moves unknown