NHTorres
NHTorres

Reputation: 1538

change text color item menu

I'm trying to change the font color of a single MenuItem in my ActionBar but can not. I am using the following code:

int positionOfMenuItem = 0; 
MenuItem item = menu.getItem(positionOfMenuItem);
SpannableString s = new SpannableString("Validar Todas");
s.setSpan(new ForegroundColorSpan(Color.WHITE), 0, s.length(), 0);
item.setTitle(s);

The text changes, but the color doesn't.

Upvotes: 0

Views: 254

Answers (1)

Jared Rummler
Jared Rummler

Reputation: 38121

This worked for me in a simple example I wrote:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    menu.add(0, 1, 0, "Red").setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
    getLayoutInflater().setFactory(new LayoutInflater.Factory() {

        @Override
        public View onCreateView(String name, Context context, AttributeSet attrs) {
            // If you are using AppCompat, you will need to change the string below.
            if (name.equalsIgnoreCase("com.android.internal.view.menu.ActionMenuItemView")) {
                try {
                    LayoutInflater f = getLayoutInflater();
                    final View view = f.createView(name, null, attrs);
                    view.post(new Runnable() {

                        public void run() {
                            TextView textView = (TextView) view;
                            // Since you only want to change it for one item you need to 
                            // check if the TextView text is the correct value.
                            if (textView.getText().toString().equals("Red")) {
                                textView.setTextColor(Color.RED);
                            }
                        }
                    });
                    return view;
                } catch (InflateException e) {
                } catch (ClassNotFoundException e) {
                }
            }
            return null;
        }
    });
    return super.onCreateOptionsMenu(menu);
}

The code you are using should work for any MenuItem in the overflow, but does not work for MenuItems that are always showing on the ActionBar.

Upvotes: 1

Related Questions