Fragment on Screen Rotation

前端 未结 2 848
礼貌的吻别
礼貌的吻别 2021-01-12 05:01

I have added a viewpager to an activity which contains two page.

In onCreate of activity I add fragments to a fragmentAdapter:

public void onCreate(B         


        
相关标签:
2条回答
  • 2021-01-12 05:31

    If you don't want to reload your fragment on orientation change, write following for the activity in which you are loading the fragment in manifest file.

    <activity
                android:name="your activity name"
                android:configChanges="orientation|screenSize" // add this to your activity
                android:label="@string/app_name">
     </activity>
    
    0 讨论(0)
  • 2021-01-12 05:37

    Every time you rotate your device you are creating a new fragment and adding it to the FragmentManager.

    All of your previously created fragments are still in the FragmentManager therefore the count increases by one each time.

    If you wish to retain a value in your fragment, you need to store it in the arguments otherwise any values it contains would be lost when the system re-creates the fragment.

    public static FragmentGame builder(long id) {
     Bundle args = new Bundle();
     args.putInt("id", id);
     fragmentGame f = new fragmentGame();
     f.setArguments(args);
    }
    

    Rather than creating a new fragment, I suspect you really want to retrieve your previously created one when you rotate the device. use getSupportFragmentManager().findFragmentById() or getSupportFragmentManager().findFragmentByTag() to do this.

    Edit: Extra code

        // Add fragment to the manager
        FragmentTransaction trans=getSupportFragmentManager().beginTransaction();
        trans.add(f,"myTag");
        trans.commit();
    
        // retrieve the fragment
        Fragment f= getSupportFragmentManager().findFragmentByTag("myTag");
    

    Just attempt to retrieve the fragment, if the value is null, create a new fragment and add it to the manager otherwise use the retrieved one.

    0 讨论(0)
提交回复
热议问题