Save status of a fragment

0

Good, I have the doubt that every Android programmer had in the beginning xD

I have an activity in which at the beginning a fragment is loaded in it, then that fragment will change for another one depending on a Drawermenu . Well, so far so good.

The problem is when I turn the screen and peta the application. I have been researching and I know that we have to work with the onSaveInstanceState() etc but I can not do it. I do not know if I have to do it in the parent activity or in the fragments = / or if I have to do something in both of them.

How should I do it?

    
asked by borjis 01.12.2016 в 13:19
source

1 answer

3

In Handling runtime changes in the Android documentation explains a little the process you must follow to control orientation or configuration changes.

For your case with Fragments I think that in the documentation link is very well explained how to manage this process. Manage it using setRetainInstance(boolean)

One way to control screen turns in the Activity is as follows:

In the manifest you declare the changes that you want to control by means of the android:configChanges tag, leaving the declaration of the activity in the following way:

<activity
     android:name=".MainActivity"
     android:configChanges="orientation|keyboardHidden|screenSize|smallestScreenSize"
     android:label="@string/app_name"
     android:theme="@style/AppThemeAction" />

And then the code that is put in the activity to pick up the configuration change events such as the change of orientation of the screen is as follows:

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    //detectamos el cambio de orientación en este caso
    if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        landscape = true;
        //acciones deseadas
    }

    if(newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
        landscape = false;
        //acciones deseadas
    }
}
    
answered by 01.12.2016 / 13:56
source