Getting a reference to a child Fragment after the parent Fragment has been recreated

前端 未结 3 1266
有刺的猬
有刺的猬 2021-01-31 19:13

Starting Android 4.2, Android supports nested Fragments. The doc doesn\'t give a lot of explanations regarding nested Fragment lifecycles but from experience, it ap

3条回答
  •  时光说笑
    2021-01-31 19:50

    are u using FragmentPagerAdapter? if not try FragmentPagerAdapter instead of FragmentStatePagerAdapter I realised that have some bug when using FragmentStatePagerAdapter when i have 4 level nest. Sorry my english is poor.

    @Override
    public void onCreate(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
         mFragment1 = getFragmentManager().getFragment(savedInstanceState, STATE_Fragment1);
         mFragment2 = getFragmentManager().getFragment(savedInstanceState, STATE_Fragment2);
         mFragment3 = getFragmentManager().getFragment(savedInstanceState, STATE_Fragment3);
        } else {
         mFragment1 = SomeFragment.newInstance("param1");
         mFragment2 = SomeFragment.newInstance("param2");
         mFragment3 = SomeFragment.newInstance("param3");
        }
        super.onCreate(savedInstanceState);
        mMyPagerAdapter = new MyPagerAdapter(getChildFragmentManager(), mFragment1, mFragment2, mFragment3);
    }
    
    @Override
    public void onSaveInstanceState(Bundle outState) {
        if (mFragment1 != null) {
            getFragmentManager().putFragment(outState, STATE_Fragment1,
                    mFragment1);
        }
    
        if (mFragment2 != null) {
            getFragmentManager().putFragment(outState, STATE_Fragment2,
                    mFragment2);
        }
    
        if (mFragment3 != null) {
            getFragmentManager().putFragment(outState, STATE_Fragment3,
                    mFragment3);
        }
    
        super.onSaveInstanceState(outState);
    }
    

提交回复
热议问题