javaandroidandroid-fragmentsandroid-activityrotation

When I rotate the screen, the fragment is destroyed and returned to Activity, which opened that Fragment. But why he's doing so?


I have an Activity which can open 2 different Fragments by 2 different Buttons. By the default that Activity when it creates, it is opening a Fragment, we call it "The Main Fragment". The first Fragment to which we are going over by the first Button we meet zero problems with the Rotation, but the second one after the rotation disappears and the screen shows the Main Fragment's content. When I tried to rotate the screen back, I see the Main Fragment's content again. But why it is so, if I didn't write any code, which must return me to the Main Fragment without clicking a button.

What assumptions do you have?


Solution

  • Why this is happening ?

    Default Behavior, Actiivty is getting recreated on orientation change so your fragment are.

    Explanation

    You need to understand Activity Life Cycle to understand why this is happening.

    enter image description here

    First, “rotating the screen” is not the actual scenario we are talking about today. Because any configuration change will cause Android to restart your Activity. A configuration change might be the device rotating (because now we have a different screen layout to draw upon), or it could be a language switch (because we need to re-write all those strings, which may need more room now OR it could be the scary RTL switch!), or even keyboard availability.

    By reloading your app, what the system is actually doing is calling onDestroy() and then immediately calling onCreate(). This way, your Activity is as fresh as possible, with all of the right creation data (even though the user has been with you the entire time).

    Now you have following option -

    1. Either Fix Orientation for your app from AndroidManifest.xml

    But oviously that is not a very good experience for user.

    1. Save activityState with onSaveInstanceState()

    This method will be called before onDestroy(). And, when your Activity is created, there’s a matching step onRestoreInstanceState(), which will also be called automatically. All of these automatic steps mean that you can let the system worry about saving and loading your data, because you planned ahead and mapped out what was important. (Or, you can skip onRestoreInstanceState() and load your saved state from the Bundle that comes with onCreate().

    In you integrate Fragment in activity, because activity is getting destroy() so your fragment will also destroy() and will be recreated.

    enter image description here

    Please take a good read on Handling Configuration Change and this.

    Once you understood the concepts things will start falling into your but it will only happen if you will complete your learning curve.

    Happy Coding !