I am a beginner in Android Development. Using android's default Navigation drawer activity I am developing an application. One of the requirements of this app is to change the background colors of layouts (including navigation drawer header color) randomly at run time.
Now everything is going fine except the color of the selected menu item on navigation drawer is still blue. like this :
Now what I want is as the background color of other layouts is pink the selected menu item on the navigation bar should also be pink (I mean the text color and the icon should be pink) like this :
Can anyone please tell how to achieve it programatically in code as I have to change selected text and icon colors at runtime randomly.
Here's the menu xml file for reference:
<?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/nav_quiz_all"
android:icon="@drawable/ic_public_black_24dp"
android:checked="true"
android:title="All Countries Quiz"/>
<item
android:id="@+id/nav_quiz_bookmarked"
android:icon="@drawable/ic_favorite_black_24dp"
android:title="Favorite Quiz"/>
</group>
<item android:title="Communicate">
<menu>
<item
android:id="@+id/nav_rate"
android:icon="@drawable/ic_star_black_24dp"
android:title="Rate this app"/>
<item
android:id="@+id/nav_share"
android:icon="@drawable/ic_share_black_24dp"
android:title="Share"/>
<item
android:id="@+id/nav_feedback"
android:icon="@drawable/ic_feedback_black_24dp"
android:title="Feedback"/>
<item
android:id="@+id/nav_about"
android:icon="@drawable/ic_info_black_24dp"
android:title="About"/>
</menu>
</item>
<item
android:id="@+id/nav_settings"
android:icon="@drawable/ic_settings_black_24dp"
android:title="Settings"/>
</menu>
I have tested this code on sdk 17 to sdk 26 code write the logic after setContent(R.layou.your_activity) find the navigation view with Id
First Way
try using:
For your
NavigationView
Second Way
For programetically change use:
Define
ColorStateList1
andColorStateList2
as:For Navigation View Item Text Color
For Navigation View Item Icon Color
Have you tried?
First check for the NavigationView below
Check here two things
These both tags are using
drawer_item_color.xml
which is a selector and below is the code for ituse selector and add colors you want. This will do the job for you.
Firstly thank you all for responding back with your solutions :) Learning from the answers above and doing some research on
ColorStateList
I finally managed to create amethod
which sets the color of the checked item on the navigation drawer to match the color of my app theme color which is generated randomly at runtime.Here's the method:
you can call this method with any
int color
you want :)