3

I'm trying to use 3 fragments in one activity and one of that fragment is set as default fragment in onCreate() method and others fragments are calling through some action, so when I rotate the screen the onCreate() method calling again and my current fragment are lost and the default fragment start again but I have to use the default fragment inside the onCreate() method. How can I keep my running fragment on rotate the screen.?

Nick Friskel
  • 2,369
  • 2
  • 20
  • 33
Sabir Hossain
  • 1,183
  • 1
  • 25
  • 46
  • 2
    Possible duplicate of [Once for all, how to correctly save instance state of Fragments in back stack?](http://stackoverflow.com/questions/15313598/once-for-all-how-to-correctly-save-instance-state-of-fragments-in-back-stack) – petey Dec 13 '16 at 19:41

3 Answers3

1

You can add android:configChanges="screenSize|orientation" on activity manifest here is examples:

<activity android:name=".MyActivity"
      android:configChanges="screenSize|orientation"
      android:label="@string/app_name">
Ucdemir
  • 2,852
  • 2
  • 26
  • 44
  • It works, I'll give you that. But I wonder: how can I make, in addition, that changes the XML variant depending on orientation as well? (it conserves the whole state, but uses same XMLs in retrieval; you know `layout/` instead of `layout-land/` etc. remains the same as drawback) – SebasSBM May 21 '23 at 00:15
0

you can use setRetainInstance(true)in your onCreate method.

To retain stateful objects in a fragment during a runtime configuration change:

Extend the Fragment class and declare references to your stateful objects.

Call setRetainInstance(boolean) when the fragment is created.

Add the fragment to your activity.

Use FragmentManager to retrieve the fragment when the activity is restarted.

see documentation of how to handle configuration changes, there is a fragment section

Community
  • 1
  • 1
Pedro Antonio
  • 250
  • 1
  • 5
  • 17
0

I'm using BottomNavigationView and I encountered the same problem. Solved it by checking if savedInstanceState is null or not before loading the default fragment.

if(savedInstanceState==null) {
   //This is the function you call onCreate to load your Fragments
   loadFragments(new MyDefaultFragment());
}
Lefty
  • 1,192
  • 13
  • 18