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
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>
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.