Search code examples
androidfragment-lifecycle

Distinguish first vs followings onCreateView's call in fragment


Probably it is a well-known topic, but I didn't find any "universal" solution.

The main problems are two:

  • When a fragment is put to backstack, onSavedInstanceState is never called
  • Why can't you instantiate fragment's views in onCreate?

And at this point my question is: since the fragment lifecycle goes through onCreateView every resume, and since we can't instantiate views in onCreate; why do we have to re-create views every time the fragment is shown? There must be a way as in the Activity with onCreate.

We might avoid by adding a class-scoped boolean and check if it has a value, but it means adding an if and this can't be the best solution. Another solution might be this one, but it is also a workaround and it also has some limitations.

Is there a built-in (or a standard) solution that solve this problem?


Solution

  • I'm unclear on the meaning of the title of your question - but I can answer these three points:

    When a fragment is put to backstack, onSavedInstanceState is never called

    onSavedInstanceState is called when saving state - just adding to the backstack is not causing that to happen - it happens when pausing the fragment if there is some UI showing. Actually a good answer addressing this problem exists here (link)

    Why can't you instantiate fragment's views in onCreate?

    A fragment is resumed from the onPostResume method of an Activity, only at this point can you safely touch the views of a fragment. (Inside the fragment you can use onViewsCreated)

    why do we have to re-create views every time the fragment is shown

    This can be avoided by retaining your fragment instances (although there are drawbacks). You can retain by using:

    setRetainInstance(true)