onCreateOptionsMenu() called twice in Fragment

bvitaliyg picture bvitaliyg · May 12, 2013 · Viewed 9k times · Source

I have a simple application with options menu, which changing at the start of fragments. The problem is that at the start any fragments except first onCreateOptionsMenu() called twice - within onCreate() and after onResume(). In onCreate() I call it manualy via setHasOptionsMenu(true), but after onResume() it should not happen. Besides, this only occurs after the first fragment started.

Here is base fragments code:

class BaseFragment extends Fragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle clicks
        return true;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // Create a menu
        super.onCreateOptionsMenu(menu, inflater);
    }
}

And the changing fragments code in Activity:

public void startFragment(BaseFragment fragment) {
    getSupportFragmentManager()
    .beginTransaction()
    .replace(android.R.id.content, fragment)
    .commit();
}

The sample does not use any external library like ActionBarSherlock, only SupportLibrary. I suppose, the problem is in FragmentTransaction replace() method, because it works fine when first fragment is starting. But I don't know, where start to solve the problem. I need exactly replace fragment in View.

Answer

C0D3LIC1OU5 picture C0D3LIC1OU5 · Jun 13, 2014

I know I am late to the party, but ran into the same issue- and my solution was actually to explicitly add

setHasOptionsMenu(false);

to my SupportFragments onCreate function. This prevents any extra calls to activities' onCreateOptionsMenu and to onPrepareOptionsMenu. Hope this helps.