|Fragment And Activity Working Together|
|Written by Mike James|
|Thursday, 27 March 2014|
Page 5 of 5
Making a Fragment persistent, so that it behaves as it would if the system didn't destroy and automatically recreate it, is the hardest part of working with and understanding Fragments. Once you have mastered this you are well on the way to using them effectively.
However, there is a trick that can make a Fragment much more persistent than its normally is and some use this to avoid all of the work we have just described.
The RetainInstance property can be used to ask the system not to destroy the Fragment, even when the Activity is destroyed for a configuration change. instead all that happens is that the Fragment is detached from the Activity and left in memory. When the Activity is recreated the Fragment is reAttached.
This means that the entire state of the Fragment is preserved, only the onAttach and onDetach events occur and the onCreateView is called to restore the Activity's View state.
You might think that you can use this to avoid some of the work in retaining state manually, but you need to know that that in some cases the Fragment will still be destroyed if the Activity is removed because of low system resources or if the user presses the back button. So you still have to deal with some persistence issues yourself.
The bottom line is:
don't use setRetainInstance(true) in an attempt to avoid handling Fragment persistence.
Its real value is in implementing more sophisticated behavior when you use a Fragment more like a background worker or when you need to use a Fragment to communicate state to other Activities.
Now you know how a Fragment's state can be persisted, how it can be initialized and how it can communicate with its Activity.
The next step is to find out how multiple Fragments can work together to produce a user interface that can accommodate a range of different screen sizes in a way that doesn't make any of them look like an afterthought.
Android Adventures - Mastering Fragments & Dialogs
This book is currently being revised. Chapter 5 and later refer to an earlier version of Android Studio - revisit for updates.
If you are interested in creating custom template also see:
To be informed about new articles on I Programmer, install the I Programmer Toolbar, subscribe to the RSS feed, follow us on, Twitter,Facebook, Google+ or Linkedin, or sign up for our weekly newsletter.
or email your comment to: email@example.com
|Last Updated ( Saturday, 25 July 2015 )|