Skip to content

Instantly share code, notes, and snippets.

@aows
Created May 27, 2015 00:10
Show Gist options
  • Save aows/0bdd2ead2fb2ed1d4872 to your computer and use it in GitHub Desktop.
Save aows/0bdd2ead2fb2ed1d4872 to your computer and use it in GitHub Desktop.
Changing text color of a MenuItem programmatically (Android)
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem settingsMenuItem = menu.findItem(R.id.action_settings);
SpannableString s = new SpannableString(settingsMenuItem.getTitle());
s.setSpan(new ForegroundColorSpan(yourColor), 0, s.length(), 0);
settingsMenuItem.setTitle(s);
return super.onPrepareOptionsMenu(menu);
}
@SwordBearer
Copy link

It doesn't work for me :(

@socar-doga
Copy link

me too It doesn't work

@edcastrohit
Copy link

above solution is work only for API >24, is any way to change menu item title color API<=24.
i found one solution but not want to use because for that we need to write separate click listener like below
TextView saveMenuItemTextView = new TextView(mContext);
saveMenuItemTextView.setTextColor(ourcolor);
MenuItem saveMenuItem = menu.findItem(R.id.update_item);
saveMenuItem.setActionView(saveMenuItemTextView);
saveMenuItemTextView.setOnClickListener(new View.OnClickListener() {
@OverRide
public void onClick(View v) {

        }
    });

@Nailik
Copy link

Nailik commented Oct 21, 2019

above solution is work only for API >24, is any way to change menu item title color API<=24.

i found a better solution i think.
Go in your menu xml and add to your items (if you don't use androidx use normal text view)

    `app:actionViewClass="androidx.appcompat.widget.AppCompatTextView"`

Then this works:

override fun onPrepareOptionsMenu(menu: Menu){
        //set the colors for android version < android 8 (because before that the spannable string builder with foregroundcolorspan doesnt work)
        menu.let {
            for (i in 0 until menu.size()) {
                val menuItem = menu.getItem(i)
                val textView = menuItem.actionView as AppCompatTextView
                textView.setTextColor(Color.BLACK)
                textView.onClick { onOptionsItemSelected(menuItem.itemId) }
                textView.text = menuItem.title
            }
        }
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment