IllegalStateException: Can't change container ID of Fragment

后端 未结 10 1694
孤街浪徒
孤街浪徒 2020-11-29 04:18

Android platform: 3.1

I am trying to move a fragment from a container A to a container B. Here follows the code to accomplish this:

private void rea         


        
10条回答
  •  难免孤独
    2020-11-29 04:59

    My solution to this problem is to re-create the fragment while keeping its state:

    FragmentTransaction ft = mFragmentManager.beginTransaction();
    ft.remove(old);
    Fragment newInstance = recreateFragment(old);
    ft.add(R.id.new_container, newInstance);
    ft.commit();
    

    With the following helper function:

    private Fragment recreateFragment(Fragment f)
        {
            try {
                Fragment.SavedState savedState = mFragmentManager.saveFragmentInstanceState(f);
    
                Fragment newInstance = f.getClass().newInstance();
                newInstance.setInitialSavedState(savedState);
    
                return newInstance;
            }
            catch (Exception e) // InstantiationException, IllegalAccessException
            {
                throw new RuntimeException("Cannot reinstantiate fragment " + f.getClass().getName(), e);
            }
        }
    

    It works for me, at least with the latest support library (r11), although I didn't test much yet.

    The extra cost is to instantiate the fragment twice.

提交回复
热议问题