Member-only story

Android — How you can easily determine if your Fragment was recreated from a previous state

And why you should be careful when using onViewCreated()

Yanneck Reiß
3 min readFeb 16, 2021
Image by Kennay Kermani

This short article is about a common problem in Android Development. How can we determine if our fragment has been recreated from a previous state?

This can mainly be a problem if you don’t make use of Jetpack’s Navigation Component and instantiate your fragments the old-fashioned way using a FragmentTransaction.

If you instantiate your fragments in the onViewCreated() method for example and use add instead of replace for your transaction, you will run into problems. You could quickly have multiple instances of your fragments in your respective container because of the fragment recreation without even noticing it.

Nevertheless which methods or non of these you are using for your Fragment, the onViewCreated() method is used by many developers to call the respective initialization functions like initialize the loading of data in your ViewModel, and much more.

The main reason for that is that if you take a look at the Fragment Lifecycle, the onViewCreated() is on one hand only called once when the Fragment gets created and on the other hand, has already access to the inflated view.

--

--

Yanneck Reiß
Yanneck Reiß

Written by Yanneck Reiß

Follow me on my journey as a professional mobile and fullstack developer

No responses yet