Android工具栏菜单按钮点击事件

Android Toolbar menu button click event

我的片段中有一个简单的工具栏。 The Toolbar has a menu associated to it (overflow menu under the 3 dots icon) and everything works pretty well - I get my click events when one of the menu items is selected.

但是,我需要在单击初始设置菜单时执行某些操作,而不是在选择其中一个菜单项时执行操作。任何想法如何做到这一点?我没有手动指定菜单 - 只是使用工具栏中内置的菜单,所以我不能只执行查找和点击...

我当前的工具栏代码:

mUIToolbar = (Toolbar) view.findViewById(R.id.toolbar);
ActionBarActivity activity = (ActionBarActivity) getActivity();
activity.setSupportActionBar(mToolbar);
activity.getSupportActionBar().setDisplayShowTitleEnabled(false);
activity.supportInvalidateOptionsMenu();

在这种情况下,您可以在 onPrepareOptionsMenu 方法中编写分析代码。每次显示菜单选项之前都会调用此方法。您可以在 Activity class;

中覆盖此方法
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    //Analytics code will go here.
    return true;
}