Skip to content Skip to sidebar Skip to footer

How Does `onviewstaterestored` From Fragments Work?

I am really confused with the internal state of a Fragment. I have an Activity holding only one Fragment at once and replaces it, if another Fragment should get shown. From the do

Solution 1:

Well, sometimes fragments can get a little confusing, but after a while you will get used to them, and learn that they are your friends after all.

If on the onCreate() method of your fragment, you do: setRetainInstance(true); The visible state of your views will be kept, otherwise it won't.

Suppose a fragment called "f" of class F, its lifecycle would go like this: - When instantiating/attaching/showing it, those are the f's methods that are called, in this order:

F.newInstance();
F();
F.onCreate();
F.onCreateView();
F.onViewStateRestored;
F.onResume();

At this point, your fragment will be visible on the screen. Assume, that the device is rotated, therefore, the fragment information must be preserved, this is the flow of events triggered by the rotation:

F.onSaveInstanceState(); //save your info, before the fragment is destroyed, HERE YOU CAN CONTROL THE SAVED BUNDLE, CHECK EXAMPLE BELLOW.
F.onDestroyView(); //destroy any extra allocations your have made//here starts f's restore process
F.onCreateView(); //f's view will be recreated
F.onViewStateRestored(); //load your info and restore the state of f's view
F.onResume(); //this method is called when your fragment is restoring its focus, sometimes you will need to insert some code here.//store the information using the correct types, according to your variables.@OverridepublicvoidonSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putSerializable("foo", this.foo);
    outState.putBoolean("bar", true);
}

@OverridepublicvoidonViewStateRestored(Bundle inState) {
    super.onViewStateRestored(inState);
    if(inState!=null) {
        if (inState.getBoolean("bar", false)) {
            this.foo = (ArrayList<HashMap<String, Double>>) inState.getSerializable("foo");
        }
    }

}

Post a Comment for "How Does `onviewstaterestored` From Fragments Work?"