Android Jetpack BottomNavigationView to navigate by NavigationUI

Last year Google has introduced a nice feature for navigation UI to make the fragment transition smooth and simpler. As an android developer, we all-knowing about the pain of fragment transaction which is very difficult to maintain the back stack. Now Google has improved the navigation by introducing the Navigation Controller to navigation easily. Navigation Jetpack library is now in the stable in production. It has removed all boilerplate code of fragment transactions.

How to get Started Navigation?

First of all, you need to add a few dependencies into your Gradle build file and if you want to pass a few objects from one fragment to other fragments then you need to add one more plugin to passing data from fragment to fragment becomes so easy and simple. Here are all the dependency required to add …

//plugin for passing data through navigation
apply plugin: 'androidx.navigation.safeargs'

// navigation ktx
    implementation "androidx.navigation:navigation-ui-ktx:2.1.0"
    implementation "androidx.navigation:navigation-fragment-ktx:2.1.0"

and add this to the project Gradle file.

  classpath 'android.arch.navigation:navigation-safe-args-gradle-plugin:1.0.0'

Ok, all the setting for dependency library is done here. Now, you need do to create the navigation directory inside the res folder of your project and create the navigation graph for a transaction of the fragment and call navigate method of NavController bypassing Destination ID or Action ID on user action(like button press) and it will take care of either fragment transaction or starting activity depending on your destination.

As in this article, I am going to share the bottom view navigation from one item to another item and use action by click to any view to navigation to another fragment destination and navigate back to an initial state of navigation start destination.

Here is the navigation graph nav_graph.xml

<?xml version="1.0" encoding="utf-8"?>
<navigation 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:id="@+id/nav_graph"
 app:startDestination="@+id/home_destination">

 <fragment
  android:id="@+id/home_destination"
  android:name="com.sunil.androidjetpackcomponent.ui.HomeFragment"
  android:label="Home"
  tools:layout="@layout/fragment_home" >

  <!-- Go to Detail Fragment (Its graph is responsible to handle response) -->
  <action android:id="@+id/action_homeFragment_to_DetailFragment"
   app:destination="@id/nav_detail">
   <argument android:name="movie_id" app:argType="string"/>
  </action>
 </fragment>
 <fragment
  android:id="@+id/shop_destination"
  android:name="com.sunil.androidjetpackcomponent.ui.FavoriteFragment"
  android:label="Favorite"
  tools:layout="@layout/fragment_shop">
 </fragment>

 <include app:graph="@navigation/nav_detail"/>

</navigation>

Now when the user clicks on any item view of RecyclerView, I want to navigation from the dashboard to DetailFragment destination. So here I am adding one more navigation graph inside the navigation directory.

Here is the detail of the nav_detail.xml file.

<?xml version="1.0" encoding="utf-8"?>
<navigation 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:id="@+id/nav_detail"
    app:startDestination="@id/detailFragment">

    <!-- Detail Fragment -->
    <fragment
        android:id="@+id/detailFragment"
        android:name="com.sunil.androidjetpackcomponent.ui.detail.MovieDetailFragment"
        android:label="movie's detail"
        tools:layout="@layout/fragment_detail">
        <argument
            android:name="movie_id"
            app:argType="string" />

    </fragment>

</navigation>

We have done the navigation graph here and now we need to decide the NavHost to provide this navigation graph with our activity XML file.

Here is the main-activity.xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimary"
        android:theme="@style/ThemeOverlay.AppCompat.Dark" />

    <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        app:defaultNavHost="true"
        app:navGraph="@navigation/nav_graph" />

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottom_nav"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:menu="@menu/bottom_nav_menu">
    </com.google.android.material.bottomnavigation.BottomNavigationView>>
</LinearLayout>

Now we need to get the NavController to set up the bottom navigation View.

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        setSupportActionBar(toolbar)

        val navigationController = Navigation.findNavController(this, R.id.nav_host_fragment)

        setupBottomNav(navigationController)
    }

    private fun setupBottomNav(navigationController: NavController) {

        bottom_nav?.let { NavigationUI.setupWithNavController(it, navigationController) }

    }
}

So when you open the application then navigation controller will start navigated from the start destination of our navigation. Now let’s see how can we navigate while clicking or taking Action of any item of recycler view? Here we want to navigation from dashboard/home to detail fragment destination.

adapter.onItemClick = { movie -> navigateToDetail(movie.id.toString()) }
   fun navigateToDetail(movieID: String) {
        val navController = Navigation.findNavController(requireActivity(), R.id.nav_host_fragment)
        val homeFragmentDirections =
            HomeFragmentDirections.actionHomeFragmentToDetailFragment(movieID)
        navController.navigate(homeFragmentDirections)
    }

Now suppose I required to pass some data from home to detail fragment, then it becomes super easy now with Jetpack Navigation. As you can see the above snippet code to get the direction and pass the required data and give information to the navigation controller to navigate to the destination.

Now the question of how can we receive this data to the Detail fragment? So it is also very simple to receive the data.

class MovieDetailFragment : Fragment() {
    
    private lateinit var rootView: View
    private val args: MovieDetailFragmentArgs by navArgs()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        rootView = inflater.inflate(R.layout.fragment_detail, container, false)

        val movieID = args.movieId

        return rootView
    }

Here as you see that I just use to get the extension function of navigation fragment navArgs and just received the movieID which is passed on from the home fragment.

Overall Jetpack makes android development easy and it helps you to focus more on your app’s business logic rather than spending more time on framework-specific implementations.

I have written another article related to Jetpack Navigation in detail Please check this also for a better understanding of the navigation View.

Wrapping 

Now we have a good understanding of the new android Jetpack Component Navigation. We have played with a sample project to learn the basic concept of Navigation. I personally like this change from Google. You can get the full Github source code of Jetpack Component. So my next tutorial, we will learn some other jetpack Components in detail, ok till then enjoy your healthy day.

If you are wondering to learn Android then Please learn from Android category and wondering to learn Kotlin then Kotlin Category will help you. If you want to learn all the python article, then learn from the python category.

Happy Coding 🙂

0 0 votes
Article Rating

Recent Posts

Hide your production API key or any sensitive data in Android

Hi everyone, In this article, we are going to learn how to hide the production… Read More

2 years ago

How to handle the localisation or multi language support in android with examples?

Hello everyone, Today in this article, we are going to learn about localisation to support… Read More

2 years ago

How to convert any callback to Coroutines and use them in Kotlin Android?

Hello everyone, In this article, we are going to learn something to handle the callback… Read More

2 years ago

Request Permission Launcher with Kotlin in Android

In this article, we are learning about the run time permissions for request permission launchers.… Read More

2 years ago

Implement the SMS User Consent API and SMS Retriever API in Android

Hello everyone. In my last tutorial, we learned about the Jetpack Compose introduction and about applying the… Read More

3 years ago

Jetpack Compose Coroutine flow with LiveData/ViewModel in Android

Hello everyone, In this article, we are going to learn about the Jetpack Compose with… Read More

3 years ago