Android AHBottomNavigation Bar - Tabs with ListViews

May 16, 2018 Oclemy Android BottomNavigation, Android ListView 8 minutes, 47 seconds

In this tutorial we want to see how to switch through data in ListViews via BottomNavigationItems.

We specifically use AHBottomNavigation library to create flexible tabs that are awesome and easy to customize and work with.

When user clicks a Tab or BottomNavigation Item we show different set of category of data in ListView.

What is AHBottomNavigation?

AHBottomNavigation is a library to reproduce the behavior or Bottom navigation guidelines.

This library is open source and freely available here in github.

We are Building a Vibrant YouTube Community

We have a fast rising YouTube Channel of friends. So far we've accumulated almost 3 million agreggate views and more than 10,000 subscribers as of the time of writing this. Here's the Channel: ProgrammingWizards TV.

Please go ahead subscribe(free obviously) as well. If you have a question or a comment you can post there instead of in this site.People are suggesting us tutorials to do there so you can too.

Here this tutorial in video version:

Features of AHBottomNavigation

  1. It does implement the material guidlines defined for bottom navigation.
  2. It allows you to add 3-5 items( with title,color and icon).
  3. Styles are choosable, classic or colored.
  4. You can listen to OnTabSelection events so as to detect tab selection.
  5. Supports icon font color.
  6. You can manage notifications individually for bottom navigation items.
  7. It allows you to enable or disable state.

How is AHBottomNavigation installed?

Well AHBottomNavigation can be installed into a project via Gradle:

You just add the implementation statement in your dependencies inside the app level build.gradle:

implementation 'com.aurelhubert:ahbottomnavigation:2.1.0'

Please make sure to check the latest version here.

Project Structure

Kotlin Android BottomNavigation with ListViews

Build.gradle

Our app level build.gradle.

We add AHBottomNavigation implementation statement:

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    testImplementation 'junit:junit:4.12'
    implementation 'com.aurelhubert:ahbottomnavigation:2.1.0'
}

activity_main.xml

Our xml layout. It will contain a ListView and AHBottomNavigation xml view at the bottom of our layout.

First we specify a RelativeLayout as our root tag.

The add a textview as our header label. We will be switching the data in this TextView as the selected tab changes.

We also add a ListView, which will render a given category that is selected in our bottom navigation tabs.

Lastly we will add the AHBottomNavigation element and align it to the bottom of the parent. In this case the parent is the RelativeLayout.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="info.camposha.javabottomnavigationlistview.MainActivity">

    <TextView
        android:id="@+id/headerLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:fontFamily="casual"
        android:text="Cosmic Bodies"
        android:textAllCaps="true"
        android:textSize="24sp"
        android:textStyle="bold" />
    <ListView
        android:id="@+id/myListView"
        android:padding="5dp"
        android:layout_below="@id/headerLabel"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <com.aurelhubert.ahbottomnavigation.AHBottomNavigation
        android:id="@+id/bottom_navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"/>
</RelativeLayout>

strings.xml

In the strings.xml resource, under the resource specify our three bottom navigation items or tabs add the following:

<resources>
    ....
    <string name="tab1">Planets</string>
    <string name="tab2">Stars</string>
    <string name="tab3">Galaxies</string>
    ....
</resources>

Those strings will represent our bottom navigation tab titles.Placing them in strings.xml allows us for their easy translation to other languages as well.

colors.xml

We also need some custom colors so add the below colors under the resource in your colors.xml:

<resources>
    ....
    <color name="color_tab_1">#455C65</color>
    <color name="color_tab_2">#00886A</color>
    <color name="color_tab_3">#8B6B62</color>
    <color name="color_tab_4">#6C4A42</color>
    <color name="color_tab_5">#F63D2B</color>
    ....
</resources>

These colors will be used to color our bottom navigation tabs.

MainActivity.java

Our main and only activity. Our launcher activity as well.

1. Specify Imports

We specify the package name then add our imports:

package info.camposha.javabottomnavigationlistview;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.aurelhubert.ahbottomnavigation.AHBottomNavigation;
import com.aurelhubert.ahbottomnavigation.AHBottomNavigationItem;

import java.util.ArrayList;

Among our imports include our adapterview ListView, our adapter ArrayAdapter, our AHBottomNavigation which represents our bottom navigation bar, then our AHBottomNavigationItem which represents our bottom navigation tab.

2. Create our Class

The class is MainActivity and inherits from android.app.Activity, and has probably been added to you by android studio.

public class MainActivity extends Activity {..}

3. Define Instance Fields

These instance fields include AHBottomNavigation, a TextView, a ListView, an ArrayAdapter and an integer that reprsents a cosmicCategory:

    AHBottomNavigation bottomNavigation;
    TextView headerTxt;
    ListView myListView;
    ArrayAdapter<String> adapter;
    private int cosmicCategory = 0;

4. Define and Return a Given Category Data

Our data in this case is cosmic bodies. We will be swicthing through various categories and populating an arraylist based on the current category.

That arraylist will later be used to populate a ListView via an adapter.

    private ArrayList<String> getCosmicBodies()
    {
        ArrayList<String> data=new ArrayList<>();
        data.clear();
        switch (cosmicCategory) {
            case 0:
                headerTxt.setText("Planets");
                data.add("Mercury");
                data.add("Venus");
                data.add("Earth");
                data.add("Mars");
                data.add("Jupiter");
                data.add("Saturn");
                data.add("Uranus");
                data.add("Neptune");
                break;
            case 1:
                headerTxt.setText("Stars");
                data.add("VY Canis Majos");
                data.add("UY Scuti");
                data.add("Beattleguse");
                data.add("Aldebaran");
                data.add("Epsilon Canis Majos");
                data.add("Dhube");
                data.add("Sun");
                data.add("Alpha Centauri");
                break;
            case 2:
                headerTxt.setText("Galaxies");
                data.add("IC 1011");
                data.add("Andromeda");
                data.add("Large Magellonic Cloud");
                data.add("Centaurus A");
                data.add("StarBust");
                data.add("Whirlpool");
                data.add("Cartwheel");
                data.add("Sombrero");
                break;
            default:
                break;

        }
        return data;
    }

5. Bind Data

First we instantiate an ArrayAdapter, which is our adapter. Then we set it to our ListView via the setAdapter() method.

    private void bindData()
    {
        adapter= new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, getCosmicBodies());
        myListView.setAdapter(adapter);
    }

6. Create BottonNavigation Items

We instantiate them passing in the tab title reference from the strings.xml, then the drawable image resource and color resource as well. In this case our bottom navigation tabs will show titles, drawable images and also have custom colors.

        AHBottomNavigationItem item1 = new AHBottomNavigationItem(R.string.tab1, R.drawable.ic_maps_place, R.color.color_tab_1);
        AHBottomNavigationItem item2 = new AHBottomNavigationItem(R.string.tab2, R.drawable.ic_maps_local_bar, R.color.color_tab_2);
        AHBottomNavigationItem item3 = new AHBottomNavigationItem(R.string.tab3, R.drawable.ic_maps_local_restaurant, R.color.color_tab_3);

7. Add BottomNavigation Items

We add our bottom navigation items to our bottomNavigation bar.

        bottomNavigation.addItem(item1);
        bottomNavigation.addItem(item2);
        bottomNavigation.addItem(item3);

Listen to Bottom Navigation Tab Selection events

When a bottom navigation item or tab is selected, we will assign the value of the position of that tab as our category.

Then we bind the data via the bindData() method.

        bottomNavigation.setOnTabSelectedListener(new AHBottomNavigation.OnTabSelectedListener() {
            @Override
            public boolean onTabSelected(int position, boolean wasSelected) {
                cosmicCategory = position;
                bindData();
                return true;
            }
        });

Here's the full code.

Full Code

Our main activity java code:

package info.camposha.javabottomnavigationlistview;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.aurelhubert.ahbottomnavigation.AHBottomNavigation;
import com.aurelhubert.ahbottomnavigation.AHBottomNavigationItem;

import java.util.ArrayList;

public class MainActivity extends Activity {

    /*
    Instance Fields
     */
    AHBottomNavigation bottomNavigation;
    TextView headerTxt;
    ListView myListView;
    ArrayAdapter<String> adapter;
    private int cosmicCategory = 0;

    /*
    when activity is created, setContentView, initializeViews and create navigationitems
    */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        this.initializeViews();
        this.createNavigationItems();
    }
    /*
    Initialize AHBottomNavigation, TextView and Spinner
    */
    private void initializeViews()
    {
        bottomNavigation=findViewById(R.id.bottom_navigation);
        headerTxt=findViewById(R.id.headerLabel);
        myListView=findViewById(R.id.myListView);

        //gridview item selection events
        myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                Toast.makeText(MainActivity.this, getCosmicBodies().get(position), Toast.LENGTH_SHORT).show();
            }
        });

    }
    /*
    Bind data to spinner using an ArrayAdapter
     */
    private void bindData()
    {
        adapter= new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, getCosmicBodies());
        myListView.setAdapter(adapter);
    }
    /*
    Populate an arraylist that will act as our data source.
     */
    private ArrayList<String> getCosmicBodies()
    {
        ArrayList<String> data=new ArrayList<>();
        data.clear();
        switch (cosmicCategory) {
            case 0:
                headerTxt.setText("Planets");
                data.add("Mercury");
                data.add("Venus");
                data.add("Earth");
                data.add("Mars");
                data.add("Jupiter");
                data.add("Saturn");
                data.add("Uranus");
                data.add("Neptune");
                break;
            case 1:
                headerTxt.setText("Stars");
                data.add("VY Canis Majos");
                data.add("UY Scuti");
                data.add("Beattleguse");
                data.add("Aldebaran");
                data.add("Epsilon Canis Majos");
                data.add("Dhube");
                data.add("Sun");
                data.add("Alpha Centauri");
                break;
            case 2:
                headerTxt.setText("Galaxies");
                data.add("IC 1011");
                data.add("Andromeda");
                data.add("Large Magellonic Cloud");
                data.add("Centaurus A");
                data.add("StarBust");
                data.add("Whirlpool");
                data.add("Cartwheel");
                data.add("Sombrero");
                break;
            default:
                break;

        }
        return data;
    }
    /*
    Create AHBottonNavigationItems, add them to BottomNavigation, setBackgroundColor, Listen to tab events
    */
    private void createNavigationItems()
    {
        // Create AHNavigationItems
        AHBottomNavigationItem item1 = new AHBottomNavigationItem(R.string.tab1, R.drawable.ic_maps_place, R.color.color_tab_1);
        AHBottomNavigationItem item2 = new AHBottomNavigationItem(R.string.tab2, R.drawable.ic_maps_local_bar, R.color.color_tab_2);
        AHBottomNavigationItem item3 = new AHBottomNavigationItem(R.string.tab3, R.drawable.ic_maps_local_restaurant, R.color.color_tab_3);

        // Add AHNavigationItems
        bottomNavigation.addItem(item1);
        bottomNavigation.addItem(item2);
        bottomNavigation.addItem(item3);

        // Set default background color for AHBottomNavigation
        bottomNavigation.setDefaultBackgroundColor(Color.parseColor("#FEFEFE"));

        // Change colors for AHBottomNavigation
        bottomNavigation.setAccentColor(Color.parseColor("#F63D2B"));
        bottomNavigation.setInactiveColor(Color.parseColor("#747474"));

        // Force to tint the drawable (useful for font with icon for example)
        bottomNavigation.setForceTint(true);

        // Manage titles for AHBottomNavigation
        //bottomNavigation.setTitleState(AHBottomNavigation.TitleState.SHOW_WHEN_ACTIVE);
        bottomNavigation.setTitleState(AHBottomNavigation.TitleState.ALWAYS_SHOW);
        //bottomNavigation.setTitleState(AHBottomNavigation.TitleState.ALWAYS_HIDE);

        // Use colored navigation with circle reveal effect
        bottomNavigation.setColored(true);

        // Set current item programmatically
        bottomNavigation.setCurrentItem(0);
        bindData();

        // set On TabSelectedListener
        bottomNavigation.setOnTabSelectedListener(new AHBottomNavigation.OnTabSelectedListener() {
            @Override
            public boolean onTabSelected(int position, boolean wasSelected) {
                cosmicCategory = position;
                bindData();
                return true;
            }
        });
    }
}

Result

Android Java BottomNavigationBar with ListView

Android Java BottomNavigationBar with ListView

Android Java BottomNavigationBar with ListView

Best regards.

Comments