我带有导航抽屉的mian活动,以及带有一些选项菜单的片段页面 .
然后我在片段“onCreateView”中放入“setHasOptionsMenu(true)”,然后覆盖片段的“onCreateOptionsMenu” . 但我发现选项菜单的行为很奇怪:
-
从日志中我被告知片段的'onCreateOptionsMenu'被调用,但有时候选项只是拒绝显示 .
-
如果有选项,那么我拉出抽屉,操作栏的 Headers 更改为应用程序的名称,但片段的选项也在那里 . 通过检查日志我发现"onCreateOptionsMenu"被调用两次,一个在抽屉打开后,另一个在抽屉关闭后 . 日志:
D / MainActivity:onCreateOptionsMenu < - 1 D / DeviceFragment:onCreateOptionsMenu < - 2 D / DeviceFragment:onCreateOptionsMenu < - 3
当抽屉打开时,按顺序调用“1”和“2”,当抽屉关闭时,调用“3” .
相关代码段:
MainActivity的onCreateOptionsMenu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
Log.d(TAG, "onCreateOptionsMenu");
return super.onCreateOptionsMenu(menu);
}
public void restoreActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
DeviceFragments的onCreateOptionsMenu
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If the drawer is open, show the global app actions in the action bar. See also
// showGlobalContextActionBar, which controls the top-left area of the action bar.
inflater.inflate(R.menu.frag_device, menu);
super.onCreateOptionsMenu(menu, inflater);
Log.d(TAG, "onCreateOptionsMenu");
}