Change text color of MenuItem in Navigation Drawer

ezgif-3-5ca8deec47

Navigation drawer style is my worst nightmare. In my navigation drawer I have different items with different text colors. In this post I will show you how we can change MenuItems text color programmatically.

For doing this we need two methods:

  1. Set text color for menu item:
  2.   private void setTextColorForMenuItem(MenuItem menuItem, @ColorRes int color) {
        SpannableString spanString = new SpannableString(menuItem.getTitle().toString());
        spanString.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, color)), 0, spanString.length(), 0);
        menuItem.setTitle(spanString);
      }
    
  3. Reset all menu items text color:
  private void resetAllMenuItemsTextColor(NavigationView navigationView) {
    for (int i = 0; i < navigationView.getMenu().size(); i++)
      setTextColorForMenuItem(navigationView.getMenu().getItem(i), R.color.textPrimary);
  }

We are almost done, we should just set text color for each menu item in onNavigationItemSelected method like below:

  @Override
  public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    resetAllMenuItemsTextColor(navigationView);
    setTextColorForMenuItem(item, R.color.colorPrimary);

    switch (item.getItemId()) {
      case R.id.nav_search_jobs:
        setTextColorForMenuItem(item, R.color.nav_search);
        // do other stuff
        break;
      case R.id.nav_job_recommended:
        setTextColorForMenuItem(item, R.color.nav_recommendation);
        // do other stuff
        break;
    }
    ...
  }

That’s it 😉