更改文本颜色项目菜单

change text color item menu

我正在尝试更改 ActionBar 中单个 MenuItem 的字体颜色,但不能。我正在使用以下代码:

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);

文字变了,但颜色没变。

这在我写的一个简单示例中对我有用:

@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);
}

您使用的代码应该适用于溢出中的任何 MenuItem,但不适用于始终显示在 ActionBar 上的 MenuItem