Search⌘ K
AI Features

Hooking Navigation Components

Explore how to integrate navigation components in Android development using Kotlin. Learn to add a NavHostFragment and BottomNavigationView to your layouts, connect them in your activity with ViewBinding, and enable seamless screen transitions via the navigation controller.

Adding navigation components to the news activity

We’ll add a NavHost and a BottomNavigationView to activity_news.xml.

NavHost is a container that hosts fragment destinations as they are swapped from one fragment to the next.

Let’s start with the FragmentContainerView. It will be inside a frame layout nested inside a ConstraintLayout.

XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.ui.activities.NewsActivity">
<FrameLayout
android:id="@+id/flFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="@+id/bottomNavigationView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.fragment.app.FragmentContainerView
android:id="@+id/newsNavHostFragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="@navigation/news_nav_graph" />
</FrameLayout>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/bottomNavigationView"
android:layout_width="match_parent"
android:layout_height="56dp"
app:menu="@menu/bottom_navigation_menu"
app:itemBackground="@color/black"
app:itemIconTint="@drawable/bottom_selector"
app:itemTextColor="@color/white"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
  • android:name="androidx.navigation.fragment.NavHostFragment": This defines the class name of our NavHost.

  • app:navGraph="@navigation/news_nav_graph": This references the location of the navGraph, which is located inside the folder navigation with the filename news_nav_graph.

  • app:defaultNavHost="true": This ensures ...