以编程方式更改MenuItem文本颜色

dan*_*s92 16 android android-actionbar

所以我有一个菜单项,定义为:

<item
    android:id="@+id/action_live"
    android:title="@string/action_live"
    android:orderInCategory="1"
    app:showAsAction="ifRoom|withText" />
Run Code Online (Sandbox Code Playgroud)

它显示为文本,如下所示:

截图1

我想以编程方式更改"LIVE"文本颜色.我搜索了一会儿,我找到了一个方法:

全球定义:

private Menu mOptionsMenu;
Run Code Online (Sandbox Code Playgroud)

和:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    mOptionsMenu = menu;
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}
Run Code Online (Sandbox Code Playgroud)

我做:

MenuItem liveitem = mOptionsMenu.findItem(R.id.action_live);
SpannableString s = new SpannableString(liveitem.getTitle().toString());
s.setSpan(new ForegroundColorSpan(Color.RED), 0, s.length(), 0);
liveitem.setTitle(s);
Run Code Online (Sandbox Code Playgroud)

但没有任何反应!

如果我对溢出菜单的项目执行相同操作,则可以:

截图2

应用程序有一些限制:showAsAction ="ifRoom | withText"项目?有没有解决方法?

提前致谢.

小智 18

有一次参加派对的时间晚了,但我花了一些时间研究这个并找到了一个解决方案,这可能对其他试图做同样事情的人有用.哈里什·斯里德哈兰(Harish Sridharan)的一些功劳归功于我正确的方向.

您可以使用它findViewById(R.id.MY_MENU_ITEM_ID)来定位菜单项(假设已经创建和准备了菜单),并将其投射到TextViewHarish建议的实例,然后可以根据需要进行样式设置.

public class MyAwesomeActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
    super.onCreate(savedInstanceState);

    // Force invalidatation of the menu to cause onPrepareOptionMenu to be called
    invalidateOptionsMenu();
}

private void styleMenuButton() {
    // Find the menu item you want to style
    View view = findViewById(R.id.YOUR_MENU_ITEM_ID_HERE);

    // Cast to a TextView instance if the menu item was found
    if (view != null && view instanceof TextView) {
        ((TextView) view).setTextColor( Color.BLUE ); // Make text colour blue
        ((TextView) view).setTextSize(TypedValue.COMPLEX_UNIT_SP, 24); // Increase font size
    }
}

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    boolean result = super.onPrepareOptionsMenu(menu);
    styleMenuButton();
    return result;
}
Run Code Online (Sandbox Code Playgroud)

}

这里的技巧是强制菜单在活动的onCreate事件中失效(从而导致onPrepareMenuOptions比正常情况更快地调用).在此方法中,我们可以根据需要找到菜单项和样式.

  • 我正在查看为空 (3认同)
  • findViewById返回null,我使用工具栏 (2认同)

Vic*_*hoy 7

@RRP给了我一个线索,但他的解决方案对我不起作用.@Box给了另一个,但他的回答看起来有点不那么清晰.谢谢他们.所以据他们说,我有一个完整的解决方案.

private static void setMenuTextColor(final Context context, final Toolbar toolbar, final int menuResId, final int colorRes) {
    toolbar.post(new Runnable() {
        @Override
        public void run() {
            View settingsMenuItem =  toolbar.findViewById(menuResId);
            if (settingsMenuItem instanceof TextView) {
                if (DEBUG) {
                    Log.i(TAG, "setMenuTextColor textview");
                }
                TextView tv = (TextView) settingsMenuItem;
                tv.setTextColor(ContextCompat.getColor(context, colorRes));
            } else { // you can ignore this branch, because usually there is not the situation
                Menu menu = toolbar.getMenu();
                MenuItem item = menu.findItem(menuResId);
                SpannableString s = new SpannableString(item.getTitle());
                s.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, colorRes)), 0, s.length(), 0);
                item.setTitle(s);
            }

        }
    });
}
Run Code Online (Sandbox Code Playgroud)


box*_*box 5

它只在检查后成为文本视图,它的真正类是ActionMenuItemView,我们可以在其上进一步设置文本颜色,如下所示:

public static void setToolbarMenuItemTextColor(final Toolbar toolbar,
                                               final @ColorRes int color,
                                               @IdRes final int resId) {
    if (toolbar != null) {
        for (int i = 0; i < toolbar.getChildCount(); i++) {
            final View view = toolbar.getChildAt(i);
            if (view instanceof ActionMenuView) {
                final ActionMenuView actionMenuView = (ActionMenuView) view;
                // view children are accessible only after layout-ing
                actionMenuView.post(new Runnable() {
                    @Override
                    public void run() {
                        for (int j = 0; j < actionMenuView.getChildCount(); j++) {
                            final View innerView = actionMenuView.getChildAt(j);
                            if (innerView instanceof ActionMenuItemView) {
                                final ActionMenuItemView itemView = (ActionMenuItemView) innerView;
                                if (resId == itemView.getId()) {
                                    itemView.setTextColor(ContextCompat.getColor(toolbar.getContext(), color));
                                }
                            }
                        }
                    }
                });
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Div*_*mar 5

为了更改菜单项的颜色,您可以找到该项目,从中提取标题,将其放入 Spannable String 并将前景色设置为它。试试这个代码片段

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu, menu);
    MenuItem mColorFullMenuBtn = menu.findItem(R.id.action_submit); // extract the menu item here

    String title = mColorFullMenuBtn.getTitle().toString();
    if (title != null) {
        SpannableString s = new SpannableString(title);
        s.setSpan(new ForegroundColorSpan(Color.parseColor("#FFFFFF")), 0, s.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); // provide whatever color you want here.
        mColorFullMenuBtn.setTitle(s);
    }
   return super.onCreateOptionsMenu(menu);
}
Run Code Online (Sandbox Code Playgroud)