menu inflating calls multiple times at fragment's onCreateOptionsMenu

限于喜欢 提交于 2019-12-09 08:17:28

问题


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.


回答1:


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:


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

 }



回答3:


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();


来源:https://stackoverflow.com/questions/18768021/menu-inflating-calls-multiple-times-at-fragments-oncreateoptionsmenu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!