6

Possible Duplicate:
ViewPager and fragments — what's the right way to store fragment's state?

how can I save the fragment? (It is located at the activity) When I rotate the screen, the activity being restarted, fragment is re-createdenter image description here

Community
  • 1
  • 1
Max Usanin
  • 2,479
  • 6
  • 40
  • 70
  • protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ... CustomFragment fragment; if (savedInstanceState != null) { fragment = (CustomFragment) getSupportFragmentManager().findFragmentByTag("customtag"); } else { fragment = new CustomFragment(); getSupportFragmentManager().beginTransaction().add(R.id.container, fragment, "customtag").commit(); } ... } – Viral Jul 10 '16 at 12:50
  • by following above code i have posted you can save fragment state. – Viral Jul 10 '16 at 12:50

2 Answers2

13

try to use setRetainInstance(true); in your fragment's onCreate

Berťák
  • 7,143
  • 2
  • 29
  • 38
-1

You need to add orientation to android:configChanges in your AndroidManifest.xml. Per example:

   android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
Aladin Q
  • 550
  • 5
  • 12
  • explained to me what does it mean? – Max Usanin Sep 04 '12 at 12:35
  • From http://developer.android.com/guide/topics/manifest/activity-element.html is stated: _Lists configuration changes that the activity will handle itself. When a configuration change occurs at runtime, the activity is shut down and restarted by default, but declaring a configuration with this attribute will prevent the activity from being restarted. Instead, the activity remains running and its onConfigurationChanged() method is called._ – Aladin Q Sep 04 '12 at 13:01
  • yes it works, but why do people use onSaveInstanceState and onRestoreInstanceState ? maybe this http://stackoverflow.com/a/12214737/1568164 – Max Usanin Sep 04 '12 at 13:20
  • This looks ugly, but it works great !!!! Thanks. – Praween k Dec 06 '12 at 06:50
  • 1
    The works but I don't recommend it at all. Just expect your that your activity will be recreated. So your onPause() needs to store to permanent storage anything that you need to survive long periods of time, but a rotation will only need you to override onSaveInstanceState and fill out the bundle. For fragments specifically for rotations, setRetainInstance(true) will actually handle most of what people will want with regards to behaviour while rotating. – Pork 'n' Bunny May 13 '13 at 11:51