Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onCreateOptionsMenu() called twice in Fragment

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.

like image 212
bvitaliyg Avatar asked May 12 '13 09:05

bvitaliyg


2 Answers

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.

like image 130
C0D3LIC1OU5 Avatar answered Sep 20 '22 14:09

C0D3LIC1OU5


The easiest way to solve the issue is to clear the menu just before it's inflated.

menu.clear() will clear any existing menu, and start of with a fresh one.

@Override
 public void   onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
      super.onCreateOptionsMenu(menu, inflater);
      menu.clear();
      inflater.inflate(R.menu.sample_menu, menu);
 }
like image 28
capt.swag Avatar answered Sep 22 '22 14:09

capt.swag