16

I use Fragments and when I switch to nested Fragment, which implements public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) my menu inflates quantity of times when I get to that nested Fragment. How can I avoid this? I also implement constructor of Fragment with methods:

setRetainInstance(true);
setHasOptionsMenu(true);

When I tried to implement siple solution as:

 @Override
 public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
     // TODO Add your menu entries here
   if(!isInflated)
         {
         inflater.inflate(R.menu.contacts_archive_menu, menu);
         isInflated = true;
         }
         super.onCreateOptionsMenu(menu, inflater);

 }

but my menu wasn't inflate after the screen rotation.

4 Answers 4

41

I solved it simply by clearing menu before ionflating of it:

     @Override
     public void   onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
          menu.clear();
          inflater.inflate(R.menu.call_menu, menu);
          super.onCreateOptionsMenu(menu, inflater);

     }
2
  • 6
    what is this bug? any idea
    – Zeeshan
    Commented Jul 13, 2015 at 6:39
  • Thanks for this. We have an array of fragment that inflate menu. Commented Mar 17, 2020 at 9:01
8

Just check the count of menu items. Meaning menu.size()==0 ,no menu items are present,then inflate with layout menu,else don't inflate at all.

 @Override
 public void   onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
      if (menu.size() == 0)
      inflater.inflate(R.menu.call_menu, menu);
      super.onCreateOptionsMenu(menu, inflater);

 }
1
  • 1
    Great.. its best way instead of menu.clear() because in that case menu inflated all time.
    – Pranav
    Commented Apr 6, 2016 at 5:48
0

Just override the invalidateOptionsMenu, example:

private var isMenuCreated = false

...

override fun invalidateOptionsMenu() {
  Log.d("invalidateOptionsMenu")
  if (!isMenuCreated) {
    super.invalidateOptionsMenu()
  }
}

...

override fun onCreateOptionsMenu(menu: Menu): Boolean {
  ...
  isMenuCreated = true
  return true
}
-1

Use before replace.

 fragment = new EditMyProfile();
 FragmentTransaction fragmentTransactionEditProfile =getSupportFragmentManager().beginTransaction();
 getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
 fragmentTransactionEditProfile.replace(R.id.frame, fragment);
 fragmentTransactionEditProfile.commit();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.