繁体   English   中英

更改文字颜色项目菜单

[英]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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM