Sudheesh Mohan
Sudheesh Mohan

Reputation: 2769

How to give custom text colour for a single menu item in a NavigationView?

Hi I am using android NavigationView. I want to give seperate text colour for some items in the NavigationView, not for all items. OR I want to change the text colour for a single item dynamically when I select an item in the NavigationView(Only for certain items). How can I do this?

Upvotes: 11

Views: 2106

Answers (2)

ryguy
ryguy

Reputation: 481

As far as I know, this is not possible. I have searched (as I am sure you have) to try to find an example of how to accomplish this, and cannot find one.

I would really suggest creating a custom view to do what you are trying to do (which is not very well detailed in your question, so it is a bit hard to suggest an alternative). Or, if you really want to use something provided by the SDK maybe you can use the OptionsMenu (which should allow for customization of individual menu items).

EDIT: It turns out it is possible to do this without a custom view. See the accepted answer from moinkhan for details.

Upvotes: 0

Moinkhan
Moinkhan

Reputation: 12932

Yes You can do it I have also done it.

First fetch the MenuItem to 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 Below code is for your 2nd solution changing text color dynamically on Menu click..

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;
        }
    });

Upvotes: 23

Related Questions