Search code examples
androidmaterial-designdrawerlayoutandroid-design-librarynavigationview

How to customize item background and item text color inside NavigationView?


I wanna achieve something like this shown in the Material Design Docs.

colorControlHighlight is used for the Background on checked items.

I need to customize:

  • background unchecked
  • text color checked
  • text color unchecked

Solution

  • With the MaterialComponents Library you can use these attributes:

    • app:itemShapeFillColor: background item color
    • app:itemIconTint: icon tint
    • app:itemTextColor: text color

    In the layout:

    <com.google.android.material.navigation.NavigationView
        app:itemShapeFillColor="@color/shape_selector"
        app:itemIconTint="@color/icon_tint_selector"
        app:itemTextColor="@color/text_color_selector"
        ../>
    

    In a custom style:

    <style name="..." parent="Widget.MaterialComponents.NavigationView" >
       <item name="itemShapeFillColor">@color/shape_selector</item>
       <item name="itemIconTint">@color/icon_tint_selector</item>
       <item name="itemTextColor">@color/text_color_selector</item>
    </style>
    

    For the itemIconTint and itemTextColor you can use a selector like this:

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
      <item android:color="?attr/colorPrimary" android:state_checked="true"/>
      <item android:alpha="0.38" android:color="?attr/colorOnSurface" android:state_enabled="false"/>
      <item android:color="?attr/colorOnSurface"/>
    </selector>
    

    For the itemShapeFillColor you can use a selector like:

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
      <item android:alpha="0.12" android:color="?attr/colorPrimary" android:state_activated="true"/>
      <item android:alpha="0.12" android:color="?attr/colorPrimary" android:state_checked="true"/>
      <item android:color="@android:color/transparent"/>
    </selector>
    

    Just a final note. Pay attention to use to the itemBackground.
    It is set to @null to use a shaped background programmatically generated by NavigationView when itemShapeAppearance and/or itemShapeAppearanceOverlay is set (default behaviour).
    This background is styled using the itemShape* attributes.
    Setting itemBackground will overwrite the programmatic background and cause values set in the itemShape* attributes to be ignored.

    enter image description here