Why is it recommended (different sources) not to overload the constructor for Fragment
s 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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With