Android Fragment - move from one View to another?

后端 未结 6 514
有刺的猬
有刺的猬 2020-12-16 18:04

Can i first add a Fragment to a View, then \"detach\" it, and then \"re-attach\" it to another View?

In code, i want to:

fragOne one = new fragOne();         


        
6条回答
  •  萌比男神i
    2020-12-16 18:33

    Please check the solution,you need to create the new instance of the same fragment and instantiate it with state of the old fragment if you want to save the state of the old fragment.

     FragmentTransaction ft = mFragmentManager.beginTransaction();
        ft.remove(one);
        Fragment newInstance = fetchOldState(one);
        ft.add(R.id.right, newInstance);
        ft.commit();
    
    
    //TO fetch the old state
        private Fragment fetchOldState(Fragment f)
            {
                try {
                    Fragment.SavedState oldState= mFragmentManager.saveFragmentInstanceState(f);
    
                    Fragment newInstance = f.getClass().newInstance();
                    newInstance.setInitialSavedState(oldState);
    
                    return newInstance;
                }
                catch (Exception e) // InstantiationException, IllegalAccessException
                {
    
                }
            }
    

提交回复
热议问题