Home » Android » android – Fragment.newInstance() vc onSaveInstanceState()

android – Fragment.newInstance() vc onSaveInstanceState()

Posted by: admin May 14, 2020 Leave a comment

Questions:

Why is it recommended (different sources) not to overload the constructor for Fragments but use static Fragment.newInstance() with passing a Bundle to it?

When you overload a constructor you just explicitly define default one. Than, if your Fragment would be recreated for some reason you use onSaveInstanceState() with subsequent data extracting on onCreate(). The similar situation with using Fragment.newInstance(), the only difference you don’t need to create public default constructor.

Am I understanding something wrong? Thank you very much.

How to&Answers:

Why is it recommended (different sources) not to overload the constructor for Fragments but use static Fragment.newInstance() with passing a Bundle to it?

Android automatically recreates all non-retained fragments on a configuration change (e.g., screen rotation), and it will use the zero-argument constructor for that. The Bundle supplied via setArguments() is saved as part of the instance state and given to the newly-recreated fragment. Hence, you only have to implement one method (the factory method) as opposed to three (a non-zero-arguments constructor and onSaveInstanceState() and onViewStateRestored()) to take the approach that you suggest.

Am I understanding something wrong?

If it works for you, go for it. As you note, the factory method approach is a recommendation, not a requirement.

Answer:

Its better idea not to overload that constructor, because Android can kill your Fragments whenever it needs. And, to recreate them later, it’ll call the non-arguments constructor.

To retreive the paramaters, just call getArguments().

getArguments().getInt("myInt", 0);

The arguments will be available even if your Fragment is recreated.