简体   繁体   中英

What does facebook do to save the fragment state(when activity is destroyed)?

I got from Are fragments saved by default with savedInstanceState? that to "To keep a fragment when an Activity gets destroyed, so it automatically reataches, you should call `Fragment.setRetainInstance(true)'"

However on https://developers.facebook.com/docs/android/login-with-facebook/v2.1#dialogs , they did not use this method in the constructor of the fragment but was still able to retain the fragment in oncreate Their code for doing so is

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

if (savedInstanceState == null) {
    // Add the fragment on initial activity setup
    mainFragment = new MainFragment();
    getSupportFragmentManager()
    .beginTransaction()
    .add(android.R.id.content, mainFragment)
    .commit();
} else {
    // Or set the fragment from restored state info
    mainFragment = (MainFragment) getSupportFragmentManager()
    .findFragmentById(android.R.id.content);
}

}

Does anyone what trick they used to retain that fragment without using setretaininstance?

There is no trick, the FragmentManager is responsible for managing the fragments, it keeps a list of fragments added using fragment transactions and handles the back stack. When the orientation change happens, those fragments are going to be recreated automatically in order to recreate the view hierarchy as it was before the orientation change. Keep in mind that those recreated fragments are new instances. All you need to do is avoid creating the fragment if the bundle is not null, because is going to be recreated automatically. And you can ask the FragmentManager for a reference to the fragment:

mainFragment = (MainFragment) getSupportFragmentManager()
    .findFragmentById(android.R.id.content);

Now, when you set setRetainInstance(true) , the fragment is not going to be destroyed when the orientation change happens (onDestroy() is not going to be called), and the exact same instance of the fragment is going to be attached to the new Activity after the orientation change (onCreate() is not going to be called, because the fragment was never destroyed). This is helpful because the instance retains all its data accross the orientation change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM