android change option menu text color

2019-07-09 09:39发布

问题:

I have been developing app these days, the code for changing text items:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater=getMenuInflater();
    inflater.inflate(R.menu.main, menu);

        int positionOfMenuItem = 0; // or whatever...
    MenuItem item = menu.getItem(positionOfMenuItem);
    SpannableString s = new SpannableString("My red MenuItem");
    s.setSpan(new ForegroundColorSpan(Color.RED), 0, s.length(), 0);
    item.setTitleCondensed(s);
    return true;
}

it works pretty, but when I clicking the menu item it stops with error

回答1:

Use one of the Spannable flag constants as the last argument to the call to setSpan(), e.g. Spannable.SPAN_EXCLUSIVE_EXCLUSIVE. See http://developer.android.com/reference/android/text/Spannable.html.

Also, consider moving the code after inflate to onPrepareOptionsMenu().

The following post might be useful: http://www.techrepublic.com/article/style-androids-overflow-menu-using-this-sanity-saving-workaround/