Hi everyone, after the release of Jetpack in android a lot of things are changed. I have published many tutorials related to Jetpack and here is another one for you. This post is about Android Navigation Tutorial where we will be learning about another very useful architecture component which is Navigation.
In this post I will show you how you can use Navigation to navigate between fragments with Bottom Navigation View. I have already posted a tutorial about Android Bottom Navigation View. But everything in android is changing very quickly. And as a developer we need to adapt the changes as well.
So, before starting the tutorial I would like to recommend you all that start using Kotlin Language. I highly recommend that start using it, it is awesome. And that is why I will be using Kotlin for all the future posts.Â
Table of Contents
Do you prefer watching video? Here is a step by step video explanation about using Android Navigation with Bottom Navigation.
Â
We did it many times. Navigation means navigating in our application for example opening activities, displaying fragments all these are navigation. And you know that we were using the Intent thing to start our activities and Fragment Transaction to display our fragments. These methods are a bit complex so to overcome this thing, now we have the Navigation Architecture Component.
Navigation Architecture Component helps us to implement navigation very easily in our application. With navigation you do not need to write startActivity or Fragment Transaction anymore the navigation will handle everything very efficiently.
In this example we will see how we can do the fragment transactions with bottom navigation using navigation component.Â
Enough talking guys, now let’s start our project.
Creating a new Android Studio Project
- It is obvious that we need an android studio project.
- So open Android Studio and create a new project.
- Here we will select an Empty Activity to create our project.
- Now remember you need to select the Language as Kotlin and you need to check Use AndroidX artifacts. (See the above image)
Adding Dependencies
- Once your project is loaded, go to your app level build.gradle file and add these dependencies.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" implementation 'androidx.appcompat:appcompat:1.0.0-beta01' implementation 'androidx.core:core-ktx:1.1.0-alpha04' implementation 'androidx.constraintlayout:constraintlayout:1.1.2' testImplementation 'junit:junit:4.12' androidTestImplementation 'androidx.test:runner:1.1.0-alpha4' androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha4' //navigation component implementation 'android.arch.navigation:navigation-fragment-ktx:1.0.0-rc02' implementation 'android.arch.navigation:navigation-fragment:1.0.0-rc02' implementation 'android.arch.navigation:navigation-ui:1.0.0-rc02' implementation 'android.arch.navigation:navigation-ui-ktx:1.0.0-rc02' //new material design implementation 'com.google.android.material:material:1.0.0' } |
- As you can see we have added the navigation components and the new material design. You just add these dependencies in your project and sync it with gradle.
Changing Theme
- As we added the new Material Design, so we will change the theme to material component.
- So go to app -> res -> values -> styles.xml.
- And here you need to change the theme. I just changed AppCompat to MaterialComponents.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> </resources> |
- Now let’s create the BottomNavigationView in our MainActivity.
- We create an XML resource file that contains the navigation graph.
- So right click on res folder and select new Android Resource File.
- Now enter file name for your navigation resource file, and select Resource type as Navigation. (See the image below).
- The same way we will create a Menu Resource File for our Bottom Navigation View.
- Inside this file I will define 3 menus.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/homeFragment" android:title="Home" android:icon="@drawable/ic_home" /> <item android:id="@+id/favsFragment" android:title="Favourites" android:icon="@drawable/ic_favorite" /> <item android:id="@+id/settingsFragment" android:title="Settings" android:icon="@drawable/ic_settings" /> </menu> |
- You can see the ids of the menu, the id is very important. With the id it will be connected to the fragments that we are going to create.
- Got to activity_main.xml and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <fragment <strong>app:navGraph="@navigation/bottom_navigation" app:defaultNavHost="true" android:name="androidx.navigation.fragment.NavHostFragment"</strong> android:layout_weight="1" android:id="@+id/fragment" android:layout_width="match_parent" android:layout_height="0dp" /> <com.google.android.material.bottomnavigation.BottomNavigationView android:id="@+id/bottomNav" android:layout_width="match_parent" android:layout_height="wrap_content" app:menu="@menu/bottom_menu" /> </LinearLayout> |
- In the above code we have a fragment. And this is the area where we will display our fragments. These properties are very important for the fragment here.
- app:navGraph=”@navigation/bottom_navigation” here we are defining that this fragment will be using this navigation graph. And it is nothing but the Navigation Resource File that we created.
- app:defaultNavHost=”true” this is true means our navigation host can intercept when the back button is pressed.
- android:name=”androidx.navigation.fragment.NavHostFragment” Defining that the fragment is a NavHostFragment.
- The above code will generate the following layout.
Creating Fragments
- Now we will create the fragments. I will tell you the steps to create a single fragment and then you can follow the same to create the remaining two fragments.
- Right click on your package then New -> Fragment -> Fragment (Blank)
- Now you need to put the Fragment name. It will also create a layout file for your fragment.
- Make sure you are creating with Kotlin Language and also Make sure that the checkboxes are unchecked (Or it will create useless functions that we don’t need now).Â
- When you will click on Finish, a Kotlin file (the fragment) and an XML file (the layout) will be created. We will change both files.
- First come inside HomeFragment.kt.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package net.simplifiedcoding import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup <strong>import androidx.fragment.app.Fragment</strong> class HomeFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_home, container, false) } } |
- In the above code make sure you are using Fragment from the package androidx.fragment.app
- Now come inside the layout file which is fragment_home.xml and modify it as below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".HomeFragment"> <TextView android:layout_gravity="center_horizontal|center_vertical" android:layout_width="wrap_content" android:textAppearance="@style/Base.TextAppearance.AppCompat.Headline" android:layout_height="wrap_content" android:text="Home Fragment"/> </FrameLayout> |
- The same way you need to create all the other fragments (Favourites and Settings).
Assuming you have created all the fragments, let’s add navigation in our fragments and it is very easy.
- Open the navigation file that we created bottom_navigation.xml. And you need to select the Design mode from the bottom (See the image for help) because it makes the life easier.
- Now when you are in the design mode you will see an add button on the top (see the below image).
- You need to click on the button and then you need to select the fragment. Here I am selecting fragment_home. And we need to repeat the process for all fragments.
- Once you will add all fragments you will see your screen like this.
- Now it is done. But you need to confirm one thing. The ids of these fragment should match with the id we given in the Menu.
- So when you select a fragment in this screen. You see the attributes on the right side, here you can see the ID. And this ID should match with the ID inside the menu resource file. This is very important or else it will not work.Â
- Now finally come to MainActivity.kt and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
package net.simplifiedcoding import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.navigation.NavController import androidx.navigation.Navigation import androidx.navigation.ui.NavigationUI import androidx.navigation.ui.setupWithNavController import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { private lateinit var navController: NavController override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //Getting the Navigation Controller navController = Navigation.findNavController(this, R.id.fragment) //Setting the navigation controller to Bottom Nav bottomNav.setupWithNavController(navController) //Setting up the action bar NavigationUI.setupActionBarWithNavController(this, navController) } //Setting Up the back button override fun onSupportNavigateUp(): Boolean { return NavigationUI.navigateUp(navController, null) } } |
- And that’s all, now you can run your application.
- Bingo! It is working absolutely fine.
In case you are not able to create this app or having some issues following the post. You can get the source code from the GitHub repository given below.
[sociallocker id=1372] Android Navigation Tutorial Source Code Download [/sociallocker]
So that is all for this post friends. I hope you found it useful and you learned something new. If you want me to keep posting tutorials like this then please support me. You can support me by sharing this post with your friends. So please share it in your social profiles. And if you want to ask something your comments are welcome.