Created
May 27, 2015 00:10
-
-
Save aows/0bdd2ead2fb2ed1d4872 to your computer and use it in GitHub Desktop.
Changing text color of a MenuItem programmatically (Android)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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); | |
} |
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
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) {