How to integrate Navigation component with other Android components?

Integrating the Navigation Component with other Android components is essential for developing a seamless user experience. The Navigation Component simplifies the implementation of navigation within an app and works well with various Android components such as Fragments, Activities, and ViewModels.

Example of Integration

Here’s a simple example of how to integrate the Navigation component with a Fragment and a ViewModel:

// In your build.gradle file, make sure to include necessary dependencies implementation "androidx.navigation:navigation-fragment-ktx:2.3.5" implementation "androidx.navigation:navigation-ui-ktx:2.3.5" // Sample Fragment Code class MyFragment : Fragment() { private lateinit var viewModel: MyViewModel override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { viewModel = ViewModelProvider(this).get(MyViewModel::class.java) return inflater.inflate(R.layout.fragment_my, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // Set up Navigation val navController = findNavController() val navHostFragment = navController.getCurrentDestination() } } // ViewModel Code class MyViewModel(application: Application) : AndroidViewModel(application) { // ViewModel logic goes here }

Android Navigation Component Navigation in Android Android Fragments Android ViewModel Integration