更改文字颜色项目菜单

时间:2015-08-12 18:23:23

标签: android menuitem

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

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

文字会改变,但颜色不会改变。

1 个答案:

答案 0 :(得分:1)

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

@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,但不适用于始终显示在MenuItem上的ActionBar