16

我使用片段,当我切换到嵌套片段时,public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)当我到达那个嵌套片段时,它实现了我的菜单膨胀次数。我怎样才能避免这种情况?我还使用方法实现了 Fragment 的构造函数:

setRetainInstance(true);
setHasOptionsMenu(true);

当我尝试将简单的解决方案实现为:

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

 }

但屏幕旋转后我的菜单没有膨胀。

4

3 回答 3

40

我通过在 ionflating 之前清除菜单来解决它:

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

     }
于 2013-09-13T13:14:33.237 回答
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);

 }
于 2014-01-31T07:13:17.720 回答
-1

更换前使用。

 fragment = new EditMyProfile();
 FragmentTransaction fragmentTransactionEditProfile =getSupportFragmentManager().beginTransaction();
 getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
 fragmentTransactionEditProfile.replace(R.id.frame, fragment);
 fragmentTransactionEditProfile.commit();
于 2016-11-22T07:11:09.250 回答