Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
485 views
in Technique[技术] by (71.8m points)

android - Fragment.newInstance() vc onSaveInstanceState()

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...