[go: up one dir, main page]

Open In App

BottomNavigationView in Android

Last Updated : 16 Aug, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

BottomNavigationView makes it easy for users to explore and switch between top-level views with a single tap. There should be a minimum of 3 top-level views and a maximum of 5. If Destinations are more than 5 then use the Navigation Drawer. When the user taps on the icon it will change the top-level view accordingly. In a Music Player app to switch between Home, Album, and Radio, it can be used. Google plus app uses this widget to switch between different views. Instagram uses BottomNavigationView to switch between Feeds, Search, add, Like, and Profile. This is how a BottomNavigationView looks like. 

BottomNavigationView in Android

Some Advantages and Disadvantages of BottomNavigationView are: Advantages
  • It is a Top-level destination that can be accessed from anywhere in the app.
  • It is a Material Design Component.
  • Easy to use and implement.
Disadvantages 
  • It is used only when we have only three to five Destinations.
  • Can only be used with Mobile and Tablets.
  • The length of Text Labels should be less.
  • It should be used when the user will spend more than 90% of the time in an app in the same window.
  • Using with TabLayout may cause confusion to the user.
Step by Step Implementation Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.

Step 2: Adding Dependency to the build.gradle File

Add the support library in the build.gradle file and add a dependency in the dependencies section. This library has the inbuilt widget for the Bottom Navigation view so through this library it can be directly added.

implementation 'com.google.android.material:material:1.3.0-alpha03'
Step 3: Working with the XML Files

Now create a new Android Resource Directory. Right-click on the res folder and select Android Resource Directory. Make sure to select the resource type as a menu. Now create the bottom_menu.xml file and add the following code. In this file, we add the title, id, and icon of our menu for BottomNavigationView. Below is the code for the bottom_menu.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
  
    <item
        android:id="@+id/algorithm"
        android:icon="@drawable/ic_algorithm"
        android:title="Algorithm" />
  
    <item
        android:id="@+id/course"
        android:icon="@drawable/ic_course"
        android:title="Course" />
  
    <item
        android:id="@+id/profile"
        android:icon="@drawable/ic_account"
        android:title="Profile" />
</menu>


Create an AlgorithmFragment by right click on the java package, selecting new -> Fragment(Blank).

Follow the above steps for CourseFragment and LoginFragment. Now add the following code in the AlgorithmFragment.xml file. Here a TextView is added to the layout. Below is the code for the fragment_algorithm.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".Fragments.AlgorithmFragment">
  
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Algorithm"
        android:textSize="30sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>


Now add the following code in the CourseFragment.xml file.

Here a TextView is added to the layout. Below is the code for the fragment_course.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".Fragments.AlgorithmFragment">
  
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Course"
        android:textSize="30sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>


Now add the following code in the fragment_profile.xml file.

Here a TextView is added to the layout. Below is the code for the fragment_profile.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".Fragments.AlgorithmFragment">
  
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Algorithm"
        android:textSize="30sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>


Now add the following code in the activity_main.xml file. In this file, we add BottomNavigationView to our layout.

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
  
    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/bottom_navigation" />
  
    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottom_navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_gravity="bottom"
        android:background="@color/colorPrimary"
        app:itemIconTint="@android:color/white"
        app:itemTextColor="@android:color/white"
        app:menu="@menu/bottom_menu" />
</RelativeLayout>


Step 4: Working with the MainActivity File

Go to the MainActivity File and refer to the following code. Below is the code for the MainActivity File. Comments are added inside the code to understand the code in more detail. In this file, we add OnNavigationItemSelectedListener which helps to navigate between the fragments. It will switch the fragment when the user taps on the icon.

Java




import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;
  
public class MainActivity extends AppCompatActivity {
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
        bottomNav.setOnNavigationItemSelectedListener(navListener);
  
        // as soon as the application opens the first
        // fragment should be shown to the user
        // in this case it is algorithm fragment
        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new AlgorithmFragment()).commit();
    }
  
    private final BottomNavigationView.OnNavigationItemSelectedListener navListener = item -> {
        // By using switch we can easily get
        // the selected fragment
        // by using there id.
        Fragment selectedFragment = null;
        int itemId = item.getItemId();
        if (itemId == R.id.algorithm) {
            selectedFragment = new AlgorithmFragment();
        } else if (itemId == R.id.course) {
            selectedFragment = new CourseFragment();
        } else if (itemId == R.id.profile) {
            selectedFragment = new ProfileFragment();
        }
        // It will help to replace the 
        // one fragment to other.
        if (selectedFragment != null) {
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment).commit();
        }
        return true;
    };
}


Kotlin




import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.google.android.material.bottomnavigation.BottomNavigationView
  
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
  
        val bottomNav = findViewById<BottomNavigationView>(R.id.bottom_navigation)
        bottomNav.setOnNavigationItemSelectedListener(navListener)
  
        // as soon as the application opens the first fragment should
        // be shown to the user in this case it is algorithm fragment
        supportFragmentManager.beginTransaction().replace(R.id.fragment_container, AlgorithmFragment()).commit()
    }
  
    private val navListener = BottomNavigationView.OnNavigationItemSelectedListener {
        // By using switch we can easily get the
        // selected fragment by using there id
        lateinit var selectedFragment: Fragment
        when (item.itemId) {
            R.id.algorithm -> {
                selectedFragment = AlgorithmFragment()
            }
            R.id.course -> {
                selectedFragment = CourseFragment()
            }
            R.id.profile -> {
                selectedFragment = ProfileFragment()
            }
        }
        // It will help to replace the
        // one fragment to other.
        supportFragmentManager.beginTransaction().replace(R.id.fragment_container, selectedFragment).commit()
            true
    }
}


Output:


Previous Article
Next Article

Similar Reads

How to Save Fragment States with BottomNavigationView in Android?
In Android applications, Activities and Fragments are from the foundation of the UI layer. It is now standard practice to load the UI with multiple fragments. For example, Instagram, Twitter, and a slew of other well-known apps. Imagine browsing some tweets in the Twitter app's HomeFragment, navigating to the search screen, and then returning to th
4 min read
How to Hide/Show BottomNavigationView on Scroll in Android?
BottomNavigationView is the best option for navigation in Android. It makes life easier for a user to switch between multiple activities and fragments. It's really a pain in the butt to use an Android app without having proper navigation. At GFG, we have already shared an article with you on BottomNavigationView. If you are new or don't know what i
3 min read
Android | Android Application File Structure
It is very important to know about the basics of Android Studio's file structure. In this article, some important files/folders, and their significance is explained for the easy understanding of the Android studio work environment. In the below image, several important files are marked: All of the files marked in the above image are explained below
3 min read
What's Android Interface Definition Language (AIDL) in Android?
The Android Interface Definition Language (AIDL) is analogous to other IDLs you would possibly have worked with. It allows you to define the programming interface that both the client and repair agree upon so as to speak with one another using interprocess communication (IPC). Traditionally the Android way a process cannot access the memory of some
7 min read
Android | Running your first Android app
After successfully Setting up an Android project, all of the default files are created with default code in them. Let us look at this default code and files and try to run the default app created. The panel on the left side of the android studio window has all the files that the app includes. Under the java folder, observe the first folder containi
3 min read
How to Add OpenCV library into Android Application using Android Studio?
OpenCV is the huge open-source library for computer vision, machine learning, and image processing and now it plays a major role in real-time operation which is very important in today’s systems. By using it, one can process images and videos to identify objects, faces, or even the handwriting of a human. When it integrated with various libraries,
3 min read
8 Best Android Libraries That Every Android Developer Should Know
Android is an operating system which is built basically for Mobile phones. It is used for touchscreen mobile devices like smartphones and tablets. But nowadays these are utilized in Android Auto cars, TV, watches, camera, etc. Android has been one of the best-selling OS for smartphones. Android OS was developed by Android Inc. which Google bought i
5 min read
How to Add Audio Files to Android App in Android Studio?
The audio file format is a file format for saving digital audio data on a computer system and all are aware of audio files. So in this article, we are going to discuss how can we add audio files to the android app. There are three major groups of audio file formats: Format Name Description Examples Uncompressed audio formatsUncompressed audio forma
3 min read
Different Ways to Change Android SDK Path in Android Studio
Android SDK is one of the most useful components which is required to develop Android Applications. Android SDK is also referred to as the Android Software Development Kit which provides so many features which are required in Android which are given below: A sample source code.An Emulator.Debugger.Required set of libraries.Required APIs for Android
5 min read
How to Capture a Screenshot and Screen Recording of an Android Device Using Android Studio?
Android Studio is the official IDE (Integrated Development Environment) for Android app development and it is based on JetBrains’ IntelliJ IDEA software. Android Studio provides many excellent features that enhance productivity when building Android apps. Whenever we are developing an app and in that device, you don't know how to capture screenshot
2 min read
Different Ways to Fix “Select Android SDK” Error in Android Studio
Android SDK is one of the most useful components which is required to develop Android Applications. Android SDK is also referred to as the Android Software Development Kit which provides so many features which are required in Android which are given below: A sample source code.An Emulator.Debugger.Required set of libraries.Required APIs for Android
5 min read
Different Ways to Analyze APK Size of an Android App in Android Studio
APK size is one of the most important when we are uploading our app to Google Play. APK size must be considered to be as small as possible so users can visit our app and download our app without wasting so much data. In this article, we will take a look at How we can analyze our APK in Android Studio to check the APK size. Android Studio itself pro
3 min read
Different Ways to fix "Error running android: Gradle project sync failed" in Android Studio
Gradle is one of the most important components of Android apps. It handles all the backend tasks and manages all the external dependencies which we will be going to use in building our Android Application. Sometimes due to any issue or after formatting of your pc. Some of the Gradle files may get deleted unexpectedly. So when you will start buildin
3 min read
How to Fix "Android studio logcat nothing to show" in Android Studio?
Logcat Window is the place where various messages can be printed when an application runs. Suppose, you are running your application and the program crashes, unfortunately. Then, Logcat Window is going to help you to debug the output by collecting and viewing all the messages that your emulator throws. So, this is a very useful component for the ap
2 min read
How to Build a Number Shapes Android App in Android Studio?
Android is a vast field to learn and explore and to make this learning journey more interesting and productive we should keep trying new problems with new logic. So, today we are going to develop an application in android studio which tells us about Numbers that have shapes. We will be covering two types of numbers i.e. triangular and square. So, f
4 min read
How to Fix "android.os.Network On Main Thread Exception error" in Android Studio?
The main reason for Network On Main Thread Exception Error is because the newer versions of android are very strict against the UI thread abuse. Whenever we open an app, a new “main” thread is created which helps applications interact with the running components of an app’s UI and is responsible for dispatching events to assigned widgets. The entir
3 min read
10 Android Studio Tips and Tricks For Android Developers
To become a good Android developer you should be familiar with Android Studio with some of its tips and tricks. These tips and tricks will help you to become a good Android developer and it will also help you to improve your efficiency in developing Android Apps. In this article, we will be discussing 10 Android Studio, Tips, Tricks, and Resources
6 min read
Fix "Android emulator gets killed" Error in Android Studio
Sometimes, (maybe after updating Android Studio) you might encounter a strange error, which might cause you a nightmare, the error is thrown by the Studio itself and it says: Error while waiting for device: The emulator process for AVD was killed Uggh...Now, what's this error all about? Why did it happen on the system? How do I fix it? Follow the S
3 min read
How to Build Binary to Decimal Converter Android App in Android Studio?
This app will convert a Binary Number into a Decimal Number. Some people may also have written a java program to convert a Binary Number into a Decimal Number, but while making an app let's see how to do that. Brief Go Through We will start by creating a new project with an Empty Activity. After creating a project, we would add the drawable resourc
5 min read
How to Use Stack Overflow to Fix Errors During Android App Development in Android Studio?
Stack Overflow, the life savior of developers, feels like Stack Overflow is built for the developers, by the developers, of the developers. According to Wikipedia: "Stack Overflow is a question-and-answer site for professional and enthusiast programmers". So being a developer or programmer can you imagine your life without Stack Overflow…. ? Most p
4 min read
Fix "Error running android: Gradle project sync failed. Please fix your project and try again" in Android Studio
In this article, we will see how to fix the error: "Gradle project sync failed. Please fix your project and try again" in Android Studio". Before getting into the solution part, let's discuss Gradle. What is Gradle? Gradle is an open-source build automation tool that automates the creation of applications. The various steps involved in creating an
5 min read
How to Make a Scientific Calculator Android App using Android Studio?
The calculator is the app that is present on every android device. This app comes pre-installed or we can also install another application from Play Store. It is one of the most used applications for college students for making any calculations. In this article, we will take a look at building a simple scientific calculator app in Android using Kot
13 min read
How to Convert Any Website to Android App in Android Studio?
Here, we are going to make an application for the "GeeksForGeeks" website. By making this application we will be able to learn how we can convert a website to an Android Application just by following simple steps. You can use this concept for your personal website too and learn something new. What we are going to build in this article? In this appl
12 min read
Fix "Error Could not find method implementation() for arguments [com.android.support:appcompat-v7:26.0.0]" in Android Studio
Implementation is a dependency configuration used for library declaration and was introduced in the Android Gradle Plugin 3.0 by Google. Implementation dependencies are declared in this configuration which is internal and not meant for consumer exposure. The main reason for "Could not find method implementation() for arguments [com.android.support:
3 min read
How to Change App Icon of Android Programmatically in Android?
In this article, we are going to learn how to change the App Icon of an App on the Button Click. This feature can be used when we have an app for different types of users. Then as per the user type, we can change the App Icon Dynamically. Step by Step Implementation Step 1: Create a New Project To create a new project in Android Studio please refer
3 min read
Implementation of Facebook’s Android Device Year Class Library in Android
As developers, we always aim to create an application that would run smoothly on millions of devices, however, the performance of practically every application is influenced by the device specifications. There are currently over 16,000 handsets on the market with varying specifications, and the application may perform poorly on some devices when co
3 min read
Star Shower in Android using Android Property Animation
In this article, we are going to create a star shower using android property animation. We will create a slightly more involved animation, animating multiple properties on multiple objects. For this effect, a button click will result in the creation of a star with a random size, which will be added to the background container, just out of view of t
7 min read
How to Build a Prime Number Checker Android App in Android Studio?
A prime number is a natural number greater than 1, which is only divisible by 1 and itself. First few prime numbers are : 2 3 5 7 11 13 17 19 23 …... In this article, we will be building a Prime Number Checker android app in Android Studio using Kotlin and XML. The app will check whether the entered number is a Prime number or not, if the entered w
3 min read
Build an Android App with HTML, CSS and JavaScript in Android Studio
Android is a mobile operating system based on a modified version of the Linux kernel and other open-source software, designed primarily for touchscreen mobile devices such as smartphones and tablets. Yes, you read it right in the title of this article. In this article, we are going to build an Android App with HTML, CSS, and JavaScript in Android S
2 min read
Android Runtime Permissions with Dexter using Android Jetpack Compose
Android applications require the usage of hardware devices within the android applications such as microphones or cameras. For using these devices within any android application. Permissions for using this hardware have to be provided to the application. For giving these permissions to the application runtime permissions are used. Handling permissi
7 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg