在片段中使用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
中不能做什么?
这里有什么可遵循的模式吗?
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.
这篇关于在片段中使用onPrepareOptionsMenu而不是onCreateOptionsMenu的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!