为什么onCreateOptionsMenu会多次运行?(Why does onCreateOptionsMenu run multiple times?)

出于某种原因,我的onCreateOptionsMenu和onPrepareOptionsMenu运行两次(在两个方法的开头都使用日志输入进行检查)。 这种情况发生在我拥有的多个片段中,包括一些非常基本的片段(只是给菜单充气,没有别的)。

这是具有此问题的onCreateOptionsMenu之一:

@Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.actionbuttons_add_removeall, menu); optionsMenu = menu; }

UPDATE2

我发现我在Adapter的getItemCount()方法中调用.invalidateOptionsMenu() 。 我认为这会调用onPrepareOptionsMenu() ,但是阅读文档,似乎它调用onCreateOptionsMenu() 。 我可能onPrepare..() onCreate..()和onPrepare..()在此逆转,现在就检查一下。

UPDATE3

我刚刚意识到我在我的RecyclerViewAdapter的选项菜单无效,在getItemCount()方法中,这显然在首次创建片段时运行。

@Override public int getItemCount() { int tableSize = getTableSizeMethod(); if (tableSize < 1) { if (!AppManagerFragment.hideDeleteAllButton) { AppManagerFragment.hideDeleteAllButton = true; ((Activity) context).invalidateOptionsMenu(); return 0; } } else { if (!AppManagerFragment.hideDeleteAllButton) { AppManagerFragment.hideDeleteAllButton = false; ((Activity) context).invalidateOptionsMenu(); return tableSize; } } }

For some reason, my onCreateOptionsMenu and onPrepareOptionsMenu run twice (checked with a log input on the start of both methods). This happens for multiple fragments that I have, including some that are very basic (just inflating the menu, nothing else).

This is one of the onCreateOptionsMenus that has this issue:

@Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.actionbuttons_add_removeall, menu); optionsMenu = menu; }

Update2

I found out that I call .invalidateOptionsMenu() in the getItemCount() method in the Adapter. I thought that this would call onPrepareOptionsMenu(), but reading the docs, it seems like it calls onCreateOptionsMenu(). I'm probably getting onCreate..() and onPrepare..() reversed here, gonna check that out now.

Update3

I have just realized that I invalidate the options menu in my RecyclerViewAdapter, in the getItemCount() method, which obviously runs when the fragment is first created.

@Override public int getItemCount() { int tableSize = getTableSizeMethod(); if (tableSize < 1) { if (!AppManagerFragment.hideDeleteAllButton) { AppManagerFragment.hideDeleteAllButton = true; ((Activity) context).invalidateOptionsMenu(); return 0; } } else { if (!AppManagerFragment.hideDeleteAllButton) { AppManagerFragment.hideDeleteAllButton = false; ((Activity) context).invalidateOptionsMenu(); return tableSize; } } }

最满意答案

这是我自己的错。 我在我的RecyclerViewAdapter的getItemCount()方法getItemCount()选项菜单无效,这显然在启动片段时运行。 您可以查看包含我的错误的代码的问题。 感谢所有的帮助/建议。

This one was my own fault. I was invalidating the options menu in the getItemCount() method of my RecyclerViewAdapter, which obviously runs when the fragment is initiated. You can check out the question for the code that contains my error. Thanks for the help/suggestions all.

更多推荐