Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fragment.newInstance() vc onSaveInstanceState()

Tags:

android

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.

like image 769
Eugene Avatar asked Jul 22 '12 17:07

Eugene


2 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.

like image 145
CommonsWare Avatar answered Nov 07 '22 18:11

CommonsWare


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.

like image 43
Iñigo Avatar answered Nov 07 '22 20:11

Iñigo