sark9012 sark9012 - 5 months ago 21
Android Question

Material design navigation drawer item selected styling

Afternoon,

I've attempted to find the answer for this but there doesn't seem to be any direct explanation for something that I hope should be quite simple!

I've just started using the material design navigation drawer and need to change the background colour of the selected item in the drawer.

This is the code for the items within the drawer.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

<group android:checkableBehavior="single">
<item
android:id="@+id/item_1"
android:icon="@drawable/item1"
android:title="Item 1" />
<item
android:id="@+id/item_2"
android:icon="@drawable/item2"
android:title="Item 2" />
<item
android:id="@+id/item_3"
android:icon="@drawable/item3"
android:title="Item 3" />
</group>




I have the following in my MainActivity xml.

<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:background="#202020"
app:itemTextColor="@android:color/white"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_header_main"
app:menu="@menu/activity_main_drawer" />


I've managed the style the drawer with background and text colour but as mentioned above, I now need to change the background colour of the item selected.

Any help would be appreciated!

Answer Source

Add a new style to the styles.xml:

res / values / styles.xml

<style name="NavigationViewStyle">
    <item name="colorControlHighlight">#selectedItemColor</item>
</style>

Set your new style to the NavigationView:

res / layout / activity_main.xml

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/nav_header_main"
    app:menu="@menu/activity_main_drawer" 
    app:theme="@style/NavigationViewStyle" />