Search code examples
androidandroid-layoutandroid-support-librarybottomnavigationview

Android: Bottom Navigation View - change icon of selected item


I have added BottomNavigationView in my application like.

main.xml

<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" />

bottom_navigation_main.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_favorites"
        android:enabled="true"
        android:icon="@drawable/ic_favorite_white_24dp"
        android:title="@string/text_favorites"
        app:showAsAction="ifRoom" />
    <item
        android:id="@+id/action_schedules"
        android:enabled="true"
        android:icon="@drawable/ic_access_time_white_24dp"
        android:title="@string/text_schedules"
        app:showAsAction="ifRoom" />
    <item
        android:id="@+id/action_music"
        android:enabled="true"
        android:icon="@drawable/ic_audiotrack_white_24dp"
        android:title="@string/text_music"
        app:showAsAction="ifRoom" />
</menu>

MainActivity click

bottomNavigationView.setOnNavigationItemSelectedListener(
        new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.action_favorites:
                        //need change icon of favotites here.
                    case R.id.action_schedules:

                    case R.id.action_music:

                }
                return true;
            }
        });

I want to change the icon of the bottom navigation of selected position. How can we achieve this feature when user click one item?

(if user clicked one item then the icon change to another one)


Solution

  • You need to reset the icon onclick, and then on the switch case you need to set only the one you need to change, so only when selected the icon change.

    Menu menu = bottomNavigationView.getMenu();
    menu.findItem(R.id.action_favorites).setIcon(favDrawable);
    
    switch (item.getItemId()) {
                    case R.id.action_favorites:
                         item.setIcon(favDrawableSelected);
                    case R.id.action_schedules:
                    case R.id.action_music:
                }