Search code examples
androidmaterial-designandroid-bottomnav

different background color to bottom navigation tab selected item by using material design


I want to implement background color of selected item like below in the image

enter image description here

but unfortunately everyone are trying to answer this using some third party library.

I want to achieve this with material design component itself

this is my code

<com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/id_navigation_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_gravity="bottom|start"
        app:itemBackground="@android:color/white"
        app:itemIconTint="@drawable/bottom_navigation_style"
        app:itemTextColor="@drawable/bottom_navigation_style"
        app:menu="@menu/bottom_navigation_menu_items" />

style.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:color="@color/colorPrimary" android:state_selected="true" />
    <item android:color="@android:color/darker_gray" android:state_selected="false" />

</selector>

Whether it can be achieved or not with material design component only, just tell me in answer.

thanks in advance


Solution

  • Ok, Some curious thing i found is you cannot have background color and text/icon color style on same file.

    so u need two files

    bottom_navigation_style.xml

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    
        <item android:color="@color/colorPrimary" android:state_selected="true" />
        <item android:color="@android:color/darker_gray" android:state_selected="false" />
    
    </selector>
    

    bottom_navigation_style_background.xml

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    
        <item android:drawable="@color/colorPrimaryDark" android:state_checked="true" />
        <item android:drawable="@android:color/white" android:state_checked="false" />
    
    </selector>
    

    Then on activity xml you need to add to itemBackground like this

     app:itemBackground="@drawable/bottom_navigation_style_background"
     app:itemIconTint="@drawable/bottom_navigation_style"
     app:itemTextColor="@drawable/bottom_navigation_style"
    

    It will work for sure.