Search code examples
javaandroidandroid-optionsmenuoncreateoptionsmenu

Why does onCreateOptionsMenu run multiple times?


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;
}

What could cause these methods to be called multiple times (mostly twice)?


Update

I found out this is being caused (in some way) by the RecyclerView I'm using. All the views that are having this issue use a RV, the view I mentioned before that didn't have this issue, indeed doesn't. With this new info, which part of the RV could possibly be posing this issue?

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;
        }
    }
}

Solution

  • 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.