How to set custom text color for one menu item in NavigationView?

Hi, I am using android NavigationView . I want to give a separate text color for some elements in the NavigationView, and not for all elements. OR I want to change the text color for one element dynamically when I select an element in the NavigationView ( Only for certain elements ). How can i do this?

+7
android material-design navigationview
source share
2 answers

Yes you can do it. I also did it .

First select the MenuItem for which you want to change the color

Menu m = navView.getMenu(); MenuItem menuItem = m.findItem(your_menu_id); 

then apply spannable with your color

 SpannableString s = new SpannableString(menuItem.getTitle()); s.setSpan(new ForegroundColorSpan(Color.your_color), 0, s.length(), 0); menuItem.setTitle(s); 

thats it ..

Now the code below is for your 2nd solution, dynamically changing the color of the text in the menu.

 navView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(MenuItem menuItem) { SpannableString s = new SpannableString(menuItem.getTitle()); s.setSpan(new ForegroundColorSpan(Color.RED), 0, s.length(), 0); menuItem.setTitle(s); return false; } }); 
+14
source share

As far as I know, this is not possible. I was looking (as I am sure you have) to try to find an example of how to do this, and cannot find it.

I would suggest creating a custom view to do what you are trying to do (which is not well described in your question, so it’s a little difficult to suggest an alternative). Or, if you really want to use something provided by the SDK, perhaps you can use OptionsMenu (which should allow you to configure individual menu items).

EDIT: Turns out this can be done without a special look. See the accepted answer from moinkhan for details.

0
source share

All Articles