Retain The Fragment Object While Rotating

Retain the Fragment object while rotating

By default Android will retain the fragment objects. In your code you are setting the homeFragment in your onCreate function. That is why it is allways some homeFragment or fl what ever that you set in onCreate.

Because whenever you rotate, the onCreate will execute and set your fragment object to the first one

So the easy solution for you is check whether savedInstanceState bundle is null or not and set the fragment object

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

if(null == savedInstanceState) {
// set you initial fragment object
}
}

Save custom object on screen rotate in Fragment or Activity

use this code in Activity :

    if (findViewById(R.id.fragment_frame) != null) {
if (savedInstanceState != null) {
fragment =getSupportFragmentManager().getFragment(savedInstanceState,"current_fragment");

}else{
// load fragment on first time
}
}

and in fragment :

//save custom object

@Override
public void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putParcelable("key",customObject);
}

//now retrieve here

@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null)
customObject= savedInstanceState.getParcelable("key");
}

Retain ViewModels with fragment scope while rotating screen

After consulting with the Android team we figured out that it is indeed an issue within the SupportFragmentManager which is solved in v 26.+ so switching to

26.0.0-beta2

helped and now ViewModels are retained in onCreate as expected.

how can I save the fragment? when I rotate the screen

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

   android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"

How to properly retain a DialogFragment through rotation?

Inside your DialogFragment, call Fragment.setRetainInstance(boolean) with the value true. You don't need to save the fragment manually, the framework already takes care of all of this. Calling this will prevent your fragment from being destroyed on rotation and your network requests will be unaffected.

You may have to add this code to stop your dialog from being dismissed on rotation, due to a bug with the compatibility library:

@Override
public void onDestroyView() {
Dialog dialog = getDialog();
// handles https://code.google.com/p/android/issues/detail?id=17423
if (dialog != null && getRetainInstance()) {
dialog.setDismissMessage(null);
}
super.onDestroyView();
}


Related Topics



Leave a reply



Submit