Search code examples
androidandroid-layoutandroid-fragmentsfragmentfragmentmanager

FragmentManager and ScreenOrientationChanging


I have 1 activity, 2 layouts for both portrait and landscape and 2 fragments.

in portrait layout there is only 1 fragment, in landscape there are 2 fragments stand together.

when I run the activity as portrait mode at the beginning, fragmentmanager says there is only 1 fragment which is ok. Then I change the orientation and fragmentmanager says there are 2 fragments anymore which is also ok. But even though I change the orientation from landscape to portrait fragmentmanager still says there are 2 fragments. The question is that does it need to remove all fragments it has with every new oncreate? How to provide there should just 1 fragment everytime if activity creates with portrait layout?


Solution

  • I have solved the issue.

    I only remove second fragment while orientation is changing from landscape to portrait.

    Here an example:

    @Override
    public void onSaveInstanceState(Bundle state)
    {
        MySecondFragment secondFragment = (MySecondFragment) getFragmentManager().findFragmentById(R.id.secondFragment);
        if (secondFragment!=null)
        {
            FragmentManager fm = getFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();
            ft.remove(secondFragment);
            ft.commit();
        }
        super.onSaveInstanceState(state);
    
    }