I am using the new Android Design Support library to implement a navigation drawer in my application.
I can't figure out how to change the color of a selected item!
Here is the xml of the menu :
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="@+id/navigation_item_1"
android:icon="@drawable/ic_1"
android:title="@string/navigation_item_1"/>
<item
android:id="@+id/navigation_item_2"
android:icon="@drawable/ic_2"
android:title="@string/navigation_item_2"/>
</group>
And here is the navigationview xml which is placed inside a android.support.v4.widget.DrawerLayout
:
<android.support.design.widget.NavigationView
android:id="@+id/activity_main_navigationview"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/drawer_header"
app:itemIconTint="@color/black"
app:itemTextColor="@color/primary_text"
app:menu="@menu/menu_drawer">
<TextView
android:id="@+id/main_activity_version"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_marginBottom="@dimen/activity_vertical_margin"
android:layout_marginLeft="@dimen/activity_horizontal_margin"
android:textColor="@color/primary_text" />
</android.support.design.widget.NavigationView>
Thank you for your help !
[EDIT]
I have already looked at solutions such as this one : Change background color of android menu.
It seems to be quite a hack and I thought that with the new Design Support Library, something cleaner would have been introduced?
Best Solution
Well you can achieve this using Color State Resource. If you notice inside your
NavigationView
you're usingHere instead of using
@color/black
or@color/primary_test
, use aColor State List Resource
. For that, first create a newxml
(e.g drawer_item.xml) insidecolor
directory (which should be insideres
directory.) If you don't have a directory namedcolor
already, create one.Now inside
drawer_item.xml
do something like thisFinal step would be to change your
NavigationView
Like this you can use separate Color State List Resources for
IconTint
,ItemTextColor
,ItemBackground
.Now when you set an item as checked (either in
xml
or programmatically), the particular item will have different color than the unchecked ones.