Can't Change Selected Item's Background Color In Navigation Drawer
Solution 1:
I recently had the same issue and finally got to the bottom of it.
In the menu definition file @menu/activity_main_drawer
you need to add android:checkable="true"
to each item that you want to be checkable or the itemBackground
will not see the checked state.
Don't ask me why itemIconTint
and itemTextColor
work just fine without this but itemBackground
needs it, makes no sense to me either.
Solution 2:
See the Sash_KP Answer
Well you can achieve this using Color State Resource. If you notice inside your NavigationView
you're using
app:itemIconTint="@color/black"
app:itemTextColor="@color/primary_text"
Here instead of using @color/black
or @color/primary_test
, use a Color State List Resource
. For that, first create a new xml
(e.g drawer_item.xml) inside color
directory (which should be inside res
directory.) If you don't have a directory named color
already, create one.
Now inside drawer_item.xml
do something like this
<?xml version="1.0" encoding="utf-8"?><selectorxmlns:android="http://schemas.android.com/apk/res/android"><itemandroid:color="checked state color"android:state_checked="true" /><itemandroid:color="your default color" /></selector>
Final step would be to change your NavigationView
<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/drawer_item"// notice here
app:itemTextColor="@color/drawer_item"// and here
app:itemBackground="@color/drawer_item"// and here for changing the background color of the item which is checked
app:menu="@menu/menu_drawer">
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.
Solution 3:
change:
app:itemBackground="@drawable/drawer_list_selector"
to:
app:itemBackground="@color/drawer_list_selector"
move the file drawer_list_selector.xml
from /drawable/
folder to the /color/
folder (create one if it doesn't exist).
now, change the drawer_list_selector
to be a selector of colors:
<?xml version="1.0" encoding="utf-8"?><selectorxmlns:android="http://schemas.android.com/apk/res/android"><itemandroid:state_pressed="true"android:color="#F1E1F1" /><itemandroid:state_selected="true"android:color="#F1E1F1"/><itemandroid:state_checked="true"android:color="#F1E1F1"/><itemandroid:state_focused="true"android:color="#F1E1F1"/><itemandroid:state_active="true"android:color="#F1E1F1"/><itemandroid:color="@android:color/transparent" /></selector>
Post a Comment for "Can't Change Selected Item's Background Color In Navigation Drawer"