Search code examples
androidandroid-layoutandroid-xmlbottomnavigationviewmaterial-components

Android - Bottom Navigation menu selected item's icon color is not changing due to fragments


The color of the selected item of the Bottom Navigation is not changing, although i have provided the the drawable file which governs the changes of the color. I have tried so may times but i can't find the mistake in the code.

Please Help!

This is the Bottom Navigation

<com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        android:background="@color/bottomBackground"
        app:itemTextColor="@drawable/icon_color"
        app:itemIconTint="@drawable/icon_color"
        app:labelVisibilityMode="labeled"
        app:menu="@menu/bottom_navigation_menu"/>

This is the icon_color

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

Edit :

When i Remove this piece of code it works fine

        BottomNavigationView navigation = findViewById(R.id.navigation);
    navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
            int id = menuItem.getItemId();
            if(id == R.id.navigation_library) {
                loadFragment(new LibraryFragment());
            }
            else if (id == R.id.navigation_for_you) {
                loadFragment(new ForYouFragment());
            }
            return false;
        }
    });

Why does this code interfering with my feature.


Solution

  • The issue is here:

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
           ...
           return false;  //Use true in your case
        }
    

    You can check the doc:

    Returns

    boolean true to display the item as the selected item and false if the item should not be selected. Consider setting non-selectable items as disabled preemptively to make them appear non-interactive.

    Also in you layout use:

    <com.google.android.material.bottomnavigation.BottomNavigationView
            app:itemTextColor="@color/icon_color"
    

    moving the selector in the res/color folder.