Fragment Backstack is not restored when orientation changes

﹥>﹥吖頭↗ 提交于 2019-12-05 18:01:29

I think you're not checking the savedInstanceState before adding/replacing the fragment. Try this:

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Check that the activity is using the layout version
    // with the fragment_container_main FrameLayout
    if (findViewById(R.id.fragment_container_main) != null) {


        // If we're being restored from a previous state,
        // then we don't need to do anything and should return or else
        // we could end up with overlapping fragments.
        if (savedInstanceState != null) { //Do nothing, Android has got your back.

        } else {
            FragmentOne fragmentOne = new FragmentOne();

            // Add the fragment to the fragment_container_main FrameLayout
            getFragmentManager().beginTransaction()
                    .add(R.id.fragment_container_main,
                            fragmentOne,
                            "FRAG_ONE").commit();
        }
    }
}

Turns out the navigation drawer fragment was being recreated after the orientation change, so it triggered the onNavigationDrawerItemSelected, which always replaced the fragments that android was restoring. I fixed it by adding setRetainInstance(true); in my navigation drawer fragment.

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