在 Fragment 中使用 onPrepareOptionsMenu 而不是 onCreateOptionsMenu [英] Using onPrepareOptionsMenu instead of onCreateOptionsMenu in Fragment
问题描述
我在 ActionBar
中设置一些片段菜单项时遇到问题,我找到了解决方法,但我不明白为什么会这样.
I had a problem setting up some fragment menu items in the ActionBar
and I found a way to solve it, but I don't understand why it worked.
我想在使用 onCreateOptionsMenu
方法从菜单 xml 文件膨胀菜单项后立即更改菜单项的可见性.代码似乎工作正常,但没有明显的效果.我解决了在 onCreateOptionsMenu
方法中膨胀菜单的问题,但在 onPrepareOptionsMenu
方法中改变了它的可见性.
I wanted to change the visibility in a menu item right after I inflated it from a menu xml file in onCreateOptionsMenu
method. The code seems to work fine, but there's no visible effect. I solved the problem inflating the menu in onCreateOptionsMenu
method but changing the visibility of it in onPrepareOptionsMenu
method.
我想知道的是为什么更改 onCreateOptionsMenu
中的可见性不起作用.
What I want to know is why changing the visibility in onCreateOptionsMenu
does not work.
我可以在 onPrepareOptionsMenu
中做什么而在 onCreateOptionsMenu
中不能做什么?
What can I do in onPrepareOptionsMenu
that I can't do in onCreateOptionsMenu
?
这里有什么可遵循的模式吗?
Is there any pattern to follow here?
谢谢!
这是相关的代码,以防万一:
Here's the relevant code, just in case:
public class MyFragment extends Fragment {
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.my_menu, menu);
// This does not work, compiles and runs fine, but has no visible effect
MenuItem someMenuItem = menu.findItem(R.id.some_menu_item);
someMenuItem.setVisible(false);
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
// This does work
MenuItem someMenuItem = menu.findItem(R.id.some_menu_item);
someMenuItem.setVisible(false);
}
}
推荐答案
您应该在创建菜单之后而不是之前调用 super.onCreateOptionsMenu(menu, inflater);
.这会在层次结构和其他片段中向上发送菜单,或者活动可能想要自己添加项目.
You should call super.onCreateOptionsMenu(menu, inflater);
after you have created your menu, not before. That sends the menu up in the hierarchy and other fragments or the activity may want to add items themselves.
活动负责显示和管理菜单,因此如果您在将可见性发送到活动后更改可见性,则不会发生任何事情.
The activity is responsible for the displaying and managing the menu, so if you change the visibility after it has been sent to the activity, nothing much is going to happen.
现在,当你调用 super.onPrepareOptionsMenu(menu);
时,它会准备"它的菜单,但它现在将采用你在 onCreateOptionsMenu
考虑在内.
Now, when you call super.onPrepareOptionsMenu(menu);
it will "prepare" it's menu, but it will now take the changes you've made in the onCreateOptionsMenu
into account.
这篇关于在 Fragment 中使用 onPrepareOptionsMenu 而不是 onCreateOptionsMenu的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!