Kotlin Android BottomNavigationView Examples

Android BottomNavigation

Welcome to today’s tutorial. In this piece we want to look at some options for inducing  a bottom bar in your application. Mostly we will be looking at how to work with the botttom navigation bar component.

What You Will Learn

Here are the concepts you will learn in this tutorial:

  1. What is a Bottom Navigation bar
  2. How to use a bottom navigation view – simple example.
  3. How to create swipeable bottom bar.
  4. How to use BottomNavigationView with Fragments and Viewpager.
  5. How to create animated bottomnavigationview with shimmer effect.

What is a Bottom Navigation Bar?

According to android’s official documentation:

It represents a standard bottom navigation bar for application. It is an implementation of material design bottom navigation.

Bottom navigation bars make it easy for users to explore and switch between top-level views in a single tap. They should be used when an application has three to five top-level destinations.

The bar can disappear on scroll, based on HideBottomViewOnScrollBehavior, when it is placed within a CoordinatorLayout and one of the children within the CoordinatorLayout is scrolled. This behavior is only set if the layout_behavior property is set to HideBottomViewOnScrollBehavior.

The bar contents can be populated by specifying a menu resource file. Each menu item title, icon and enabled state will be used for displaying bottom navigation bar items. Menu items can also be used for programmatically selecting which destination is currently active. It can be done using MenuItem#setChecked(true).

Here are the steps followed in using a bottom navigation view:

Add it to your Layout Resource as follows:

<com.google.android.material.bottomnavigation.BottomNavigationView
     xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:app="http://schema.android.com/apk/res/res-auto"
     android:id="@+id/navigation"
     android:layout_width="match_parent"
     android:layout_height="56dp"
     android:layout_gravity="start"
     app:menu="@menu/my_navigation_items" />

Create Navigation Items menu resource file as follows:

 <menu xmlns:android="http://schemas.android.com/apk/res/android">
     <item android:id="@+id/action_search"
          android:title="@string/menu_search"
          android:icon="@drawable/ic_search" />
     <item android:id="@+id/action_settings"
          android:title="@string/menu_settings"
          android:icon="@drawable/ic_add" />
     <item android:id="@+id/action_navigation"
          android:title="@string/menu_navigation"
          android:icon="@drawable/ic_action_navigation_menu" />
 </menu>

Then lastly reference and use it in your java/kotlin code. Proceed to check our examples.

Video Tutorial

If you prefer a video tutorial then we have one:

We start by seeing what BottomNavigation is as a general design pattern, then see the BottomNavigationView for android, then look at some examples.

Bottom Navigation Example in Java

Step 1: Create Activity

MainActivity.java

Here is our main activity file. This is the only java we write in this example.

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final TextView newsTextView = findViewById(R.id.newsTextView);
        final TextView techTextView = findViewById(R.id.techTextView);
        final TextView entertainmentTextView = findViewById(R.id.entertainmentTextView);

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

        bottomNavigationView.setOnNavigationItemSelectedListener(
                new BottomNavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                        switch (item.getItemId()) {
                            case R.id.action_news:
                                newsTextView.setVisibility(View.VISIBLE);
                                techTextView.setVisibility(View.GONE);
                                entertainmentTextView.setVisibility(View.GONE);
                                break;
                            case R.id.action_tech:
                                newsTextView.setVisibility(View.GONE);
                                techTextView.setVisibility(View.VISIBLE);
                                entertainmentTextView.setVisibility(View.GONE);
                                break;
                            case R.id.action_entertainment:
                                newsTextView.setVisibility(View.GONE);
                                techTextView.setVisibility(View.GONE);
                                entertainmentTextView.setVisibility(View.VISIBLE);
                                break;
                        }
                        return false;
                    }
                });
    }
}

Step 2: Create Layout Resource

activity_main.xml

Here’s our main activity’s layout.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout

    android_layout_width="match_parent"
    android_layout_height="match_parent">

    <TextView
        android_id="@+id/newsTextView"
        android_layout_width="wrap_content"
        android_layout_height="wrap_content"
        android_layout_centerInParent="true"
        android_text="@string/txt_news" />

    <TextView
        android_id="@+id/techTextView"
        android_layout_width="wrap_content"
        android_layout_height="wrap_content"
        android_layout_centerInParent="true"
        android_text="@string/txt_tech"
        android_visibility="gone" />

    <TextView
        android_id="@+id/entertainmentTextView"
        android_layout_width="wrap_content"
        android_layout_height="wrap_content"
        android_layout_centerInParent="true"
        android_text="@string/txt_entertainment"
        android_visibility="gone" />

    <android.support.design.widget.BottomNavigationView
        android_id="@+id/bottom_navigation"
        android_layout_width="match_parent"
        android_layout_height="wrap_content"
        android_layout_alignParentBottom="true"
        app_itemBackground="@color/colorPrimary"
        app_itemIconTint="@color/white"
        app_itemTextColor="@color/white"
        app_menu="@menu/bottom_navigation_main" />

</RelativeLayout>

Step 3: Create Menu Resource file

bottom_navigation_main.xml

This is our menu. Place it under the menu resource directory.

<?xml version="1.0" encoding="utf-8"?>
<menu
    >
    <item
        android_id="@+id/action_news"
        android_enabled="true"
        android_icon="@drawable/ic_favorite_white_24dp"
        android_title="@string/txt_news"
        app_showAsAction="ifRoom" />
    <item
        android_id="@+id/action_tech"
        android_enabled="true"
        android_icon="@drawable/ic_access_time_white_24dp"
        android_title="@string/txt_tech"
        app_showAsAction="ifRoom" />
    <item
        android_id="@+id/action_entertainment"
        android_enabled="true"
        android_icon="@drawable/ic_audiotrack_white_24dp"
        android_title="@string/txt_entertainment"
        app_showAsAction="ifRoom" />
</menu>

Let’s look at some more downloadable bottomnavigationview examples.

Example 1: Kotlin Android Simple BottomNavigationView with Fragments Example

This is a simple bottom navigationview example written in Kotlin. In this example you will be able to switch through 3 fragments by clicking the corresponding bottom navigation ba item.

The fragments simply contain a textview with some text. Check the demo below:

Kotlin Android Bottom navigation example

Step 1: Dependencies

No special or third party dependency is needed.

Step 2: Design Layouts

There will be 4 layouts:

  1. 3 Fragment layouts
  2. 1 main activity layout.

Fragment Layouts

The general design of the fragment layouts is similar. All have a textview at the center that will display the text fro te chosen fragment:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Learn"
        android:textSize="35dp"
        android:gravity="center"/>

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity Layout

On the other hand the main activity layout will contain a framelayout as well as the bottomnavigationview:

<?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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <FrameLayout
        android:id="@+id/fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="0.9"/>

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottomNav"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:menu="@menu/menu_bottom_navigation"
        android:layout_weight="0.1"/>

</LinearLayout>

Step 3: Create Fragments

There will be 3 fragments:

(a). fra1.kt

The first fragment:

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment

class frag1 : Fragment() {

    override fun onCreateView(inflater: LayoutInflater,container: ViewGroup?,savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_1 , container , false)
    }

}

(b). frag2.kt

The code for the second fragment:

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment

class frag2 : Fragment() {

    override fun onCreateView(inflater: LayoutInflater,container: ViewGroup?,savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_2 , container , false)
    }

}

(c). frag3.kt

The code for the third fragment:

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment

class frag3 : Fragment() {

    override fun onCreateView(inflater: LayoutInflater,container: ViewGroup?,savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_3 , container , false)
    }

}

Step 4: Create Activity

Finally you need to create an activity that will host the fragments. The major thing here is that you will have a function that will be setting a fragment to the activity via fragment transaction as follows;

    fun setFragment(fr : Fragment){
        val frag = supportFragmentManager.beginTransaction()
        frag.replace(R.id.fragment,fr)
        frag.commit()
    }

So you willb basically be invoking this method and passing in the appropriate fragment based on the bottom navigation view item selected:

bottomNav.setOnNavigationItemSelectedListener {menu ->

            when(menu.itemId){

                R.id.btn1 -> {
                    setFragment(frag1())
                    true
                }

                R.id.btn2 -> {
                    setFragment(frag2())
                    true
                }

                R.id.btn3 -> {
                    setFragment(frag3())
                    true
                }

                else -> false
            }
        }

    }

Here is the full code;

MainActivity.kt

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.fragment.app.Fragment
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

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

        bottomNav.menu.getItem(0).isCheckable = true
        setFragment(frag1())

        bottomNav.setOnNavigationItemSelectedListener {menu ->

            when(menu.itemId){

                R.id.btn1 -> {
                    setFragment(frag1())
                    true
                }

                R.id.btn2 -> {
                    setFragment(frag2())
                    true
                }

                R.id.btn3 -> {
                    setFragment(frag3())
                    true
                }

                else -> false
            }
        }

    }

    fun setFragment(fr : Fragment){
        val frag = supportFragmentManager.beginTransaction()
        frag.replace(R.id.fragment,fr)
        frag.commit()
    }

}

Reference

Find the code reference links below:

No. Link
1. Download code
2. Browse code
3. Follow code author

Example 2 – BottomNavigationView with Fragments

In this lesson we want to explore BottomNavigationView examples. We want to look at as many examples as we can. Be aware that some examples may be using older support libraries, however you can easily update the code to androidx using android studio.

This example is written in Java. It teaches how to show bottom navigation with icons and connect each tab with Fragments.

When a tab is selected, its corresponding fragment is rendered as well.

Step 1: Create Favorites Fragment

(a). FavoritesFragmemt

Create a Favorites Fragment:

public class FavouriteFragment extends Fragment {

    public FavouriteFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_favourite, container, false);
    }
}

Step 2: Create a Video Fragment

(b). VideoFragmemt

The Videos Fragment:

public class VideoFragment extends Fragment {

    public VideoFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_video, container, false);
    }
}

Step 3: Create a Music Fragment

(c). MusicFragmemt

The Music Fragment:

public class MusicFragment extends Fragment {

    public MusicFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_music, container, false);
    }
}

Step 4: Create Main Activity

(d). MainActivity

The activity that will host all these fragments:

public class MainActivity extends AppCompatActivity {

    private Fragment fragment;
    private FragmentManager fragmentManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        fragmentManager = getSupportFragmentManager();
        fragment = new FavouriteFragment();
        final FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.add(R.id.main_container, fragment).commit();

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

        bottomNavigationView.setOnNavigationItemSelectedListener(
                new BottomNavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(MenuItem item) {
                        switch (item.getItemId()) {
                            case R.id.action_favorites:
                                fragment = new FavouriteFragment();
                                break;
                            case R.id.action_video:
                                fragment = new VideoFragment();
                                break;
                            case R.id.action_music:
                                fragment = new MusicFragment();
                                break;
                        }
                        final FragmentTransaction transaction = fragmentManager.beginTransaction();
                        transaction.replace(R.id.main_container, fragment).commit();
                        return true;
                    }
                });
    }
}

Run

If you run the project you will get the following:

BottomNavigationview Example

Download

No Link
1. Direct Download

Follow Project Author

Example 3 – BottomNavigationview with Shimmer Effect

The difference with the first example is shown in the below image:

Bottom Navigation with Shimmer

Lets go.

It only works if you set white color for background android:background="@android:color/white"

Note that ripple effect will disappear if you use app:itemBackground property.

Handling enabled/disabled state:

You need to create selector file:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:color="@color/colorPrimary" />
    <item android:color="@android:color/darker_gray"  />
</selector>

If you want change standard grey ripple effect, change colorControlHighlight property in AppTheme so it looks like following:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="colorControlHighlight">@color/colorPrimaryRipple</item>
</style>

Use 26% alpha for colored ripples.

<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryRipple">#423F51B5</color>

MainActivity

Here is the code:


public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

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

        final TextView textView = (TextView) findViewById(R.id.textView);

        bottomNavigationView.setOnNavigationItemSelectedListener(
                new BottomNavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                        switch (item.getItemId()) {
                            case R.id.action_chat:
                                textView.setText(getResources().getString(R.string.text_chat));
                                break;
                            case R.id.action_offers:
                                textView.setText(getResources().getString(R.string.text_offers));
                                break;
                            case R.id.action_notifications:
                                textView.setText(getResources().getString(R.string.text_notifications));
                                break;
                        }
                        return true;
                    }
                });
    }
}

Download Code

Direct Download

Credit

This code has been shared by @Luksha

Example 4 – BottomNavigationView with Swipeable fragments

This example improves on the other examples by adding the ability to swipe from one fragment to the other. This swipe capability is added via ViewPager.

(a). FirstFragment

The FirstFragment code:


public class FirstFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_first, container, false);
    }

}

(b). SecondFragment

The SecondFragment code:


public class SecondFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_second, container, false);
    }
}

(c). ThirdFragment

The ThirdFragment code:

public class ThirdFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_third, container, false);
    }
}

(d). OnPageChangeAdapter

The OnPageChangeAdapter code:


public abstract class OnPageChangeAdapter implements ViewPager.OnPageChangeListener {

    private int mFirstPosition = 0;

    public OnPageChangeAdapter(int firstPosition){
        mFirstPosition = firstPosition;
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        onPageSelected(mFirstPosition, position);
        mFirstPosition = position;
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    public abstract void onPageSelected(int lastposition, int position);
}

(e). MainActivity

The MainActivity code:

public class MainActivity extends AppCompatActivity {

    private BottomNavigationView mNavigationMenuView;
    private ViewPager mViewPage;

    private ArrayList<Fragment> data = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.mViewPage = (ViewPager) findViewById(R.id.view_page);
        this.mNavigationMenuView = (BottomNavigationView) findViewById(R.id.demo_navigation);

        data.add(new FirstFragment());
        data.add(new SecondFragment());
        data.add(new ThirdFragment());

        mViewPage.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return data.get(position);
            }

            @Override
            public int getCount() {
                return data.size();
            }
        });

        mViewPage.addOnPageChangeListener(new OnPageChangeAdapter(0) {

            @Override
            public void onPageSelected(int lastposition, int position) {
                mNavigationMenuView.getMenu().getItem(position).setChecked(true);
                mNavigationMenuView.getMenu().getItem(lastposition).setChecked(false);
            }
        });

        mNavigationMenuView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.action_recent:
                        mViewPage.setCurrentItem(0);
                        break;
                    case R.id.action_favorite:
                        mViewPage.setCurrentItem(1);
                        break;
                    case R.id.action_nearby:
                        mViewPage.setCurrentItem(2);
                        break;
                }
                return true;
            }
        });
    }
}

Download Code

Download code below:

No. Link
1. Download code
2. Follow Project Author

BEFORE YOU GO

YOU'VE BEEN SELECTED FOR A GIFT

Thanks for stopping by. My name is Oclemy(Clement Ochieng) and we have selected you as a recipient of a GIFT you may like ! Together with Skillshare we are offering you PROJECTS and 1000s of PREMIUM COURSES at Skillshare for FREE for 1 MONTH. To be eligible all you need is by sign up right now using my profile .

Leave a Reply

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

*

code