Bottom Navigation in Android App using Java

Bottom Navigation in Android App using Java: A Complete Guide

Bottom navigation is a popular design pattern in Android applications, used to navigate between primary destinations in an app. It helps users switch between different sections with ease and provides a consistent user experience. In this article, we’ll explore how to implement a bottom navigation bar in Android using Java, covering setup, basic usage, and tips for managing fragments.


What is Bottom Navigation?

Bottom Navigation is a bar usually positioned at the bottom of the screen, containing several icons (or labels with icons) that represent different sections of the app. When users tap on an item in the bottom navigation bar, they navigate to a different section or screen.

Android provides a ready-to-use BottomNavigationView component in the Android Material Design library, which simplifies the setup and configuration of bottom navigation in your app.


Prerequisites

Before implementing bottom navigation, make sure you have the following prerequisites:

  1. Android Studio: Ensure you have the latest version of Android Studio.
  2. Material Design Components: Add the Material Design Components library to your project’s dependencies to use BottomNavigationView.
   implementation 'com.google.android.material:material:<version>'

Replace <version> with the latest version available on Google’s Maven Repository.


Step 1: Create a New Project

  1. Open Android Studio.
  2. Create a new project, selecting an empty activity template.
  3. Choose Java as the programming language, and proceed to finish the project setup.

Step 2: Add BottomNavigationView to the Layout

In your main layout file (activity_main.xml), add a BottomNavigationView and a FrameLayout (to serve as a container for fragments) inside a ConstraintLayout or a CoordinatorLayout.

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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">

    <!-- Container for Fragments -->
    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <!-- Bottom Navigation View -->
    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottom_navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        app:menu="@menu/bottom_navigation_menu" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>

Step 3: Define the Bottom Navigation Menu

Create a new XML file for the bottom navigation menu in the res/menu folder. Name this file bottom_navigation_menu.xml.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/navigation_home"
        android:icon="@drawable/ic_home"
        android:title="Home" />

    <item
        android:id="@+id/navigation_search"
        android:icon="@drawable/ic_search"
        android:title="Search" />

    <item
        android:id="@+id/navigation_profile"
        android:icon="@drawable/ic_profile"
        android:title="Profile" />
</menu>

Ensure you have the necessary icons (ic_home, ic_search, ic_profile) in the res/drawable directory. You can find free icons on resources like Material Icons.


Step 4: Create Fragment Classes

Create individual fragments for each section that the bottom navigation will navigate to. For example, create HomeFragment, SearchFragment, and ProfileFragment by following these steps:

  1. Right-click on the java folder in your project.
  2. Select New > Java Class and name the class HomeFragment.
  3. Extend the class from Fragment and override the onCreateView method.

Example of HomeFragment:

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class HomeFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home, container, false);
    }
}

Repeat this process for SearchFragment and ProfileFragment, creating a layout file for each fragment in res/layout (e.g., fragment_home.xml, fragment_search.xml, etc.).


Step 5: Set Up Bottom Navigation in MainActivity

In your MainActivity, set up the BottomNavigationView to switch between fragments when an item is selected.

import android.os.Bundle;
import androidx.annotation.NonNull;
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);

        // Load the default fragment (e.g., HomeFragment)
        loadFragment(new HomeFragment());

        // Initialize BottomNavigationView
        BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);

        // Set up item selection listener
        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                Fragment selectedFragment = null;
                switch (item.getItemId()) {
                    case R.id.navigation_home:
                        selectedFragment = new HomeFragment();
                        break;
                    case R.id.navigation_search:
                        selectedFragment = new SearchFragment();
                        break;
                    case R.id.navigation_profile:
                        selectedFragment = new ProfileFragment();
                        break;
                }
                return loadFragment(selectedFragment);
            }
        });
    }

    // Helper method to load fragments
    private boolean loadFragment(Fragment fragment) {
        if (fragment != null) {
            getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.fragment_container, fragment)
                .commit();
            return true;
        }
        return false;
    }
}

Explanation:

  1. loadFragment is a helper method that replaces the current fragment in the fragment_container.
  2. The setOnNavigationItemSelectedListener listens for navigation item clicks and loads the corresponding fragment.

Step 6: Test the Application

Now, run the application. You should see the bottom navigation bar at the bottom of the screen, and when you tap on each item (e.g., “Home,” “Search,” or “Profile”), the corresponding fragment will load in the main content area.


Additional Tips and Best Practices

  1. Save Fragment State: If your fragments have complex state (like scrolling positions or filled forms), you may want to cache fragments to avoid reloading them every time. You can use a SparseArray or similar to keep fragment instances in memory.
  2. Highlight Selected Item: The BottomNavigationView automatically highlights the selected item based on the navigation, but you can customize its appearance by modifying the XML or applying a style.
  3. Use Navigation Component (Optional): Android’s Jetpack Navigation Component provides a more flexible and manageable way of handling navigation, including bottom navigation. If you’re working on a larger project, consider using it for smoother fragment transactions.
  4. Handle Back Navigation: By default, pressing the back button will exit the app. If you want to navigate back through the selected tabs, you may need to manage the back stack manually using FragmentManager methods.

Conclusion

Bottom navigation is a useful UI pattern for Android applications, and with BottomNavigationView, implementing it in Java is straightforward. By following the steps outlined here, you can add a bottom navigation bar to your app, enabling seamless navigation between sections. Experiment with customization and consider using Android’s Navigation Component if your app has a complex navigation structure.

With these skills, you’re ready to create engaging, user-friendly Android apps that make navigation intuitive and effective for users.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top