On Mon, Nov 28, 2011 at 1:59 PM, Doug Gordon <[email protected]> wrote: > My app is built with V4 of the Compatibility Library (in case that makes a > difference) and all of my fragments are "dynamic". That is, I explicitly > create the fragment objects and put them in a view with an "add" or similar > transaction, etc. > > What I have discovered is that, when my activity is restarted after a config > change (e.g., screen rotation), the Android framework itself automatically > reinstantiates any existing fragment objects (done in the activity's call to > super.onCreate). Due to the way I expect to start "from scratch" each time, > this caused all sorts of bizarre behavior and crashes until I figured out > what was happening. > > I've managed to basically work around this and get rid of these extraneous > fragments, but I'm thinking that I might have missed something fundamental > in how to manage these types of objects across a restart event, etc. The > documentation mentions dynamic fragments in a few places, but there seem to > be few examples or samples of how to manage them (declaring them in the xml > layout seems to be much more common). > > Anyone have any particular experience in this area?
Yeah, I need to spell this out a bit more in an upcoming book update. It confused the heck out of me too. My trial and error results match yours, apparently: If you create a dynamic fragment, and you use setRetainInstance(true), then the fragment will be carried across configuration changes. If you create a dynamic fragment, and you do NOT use setRetainInstance(true), then the old fragment will be discarded. However, after a configuration change, Android assumes you still need the fragment(s) you had before, so it creates fresh ones. The result is that, after a configuration change, you are assured of having the same number and type of fragments as you had before. It's merely a question of whether you are retaining the old fragments or are getting new instances instead. -- Mark Murphy (a Commons Guy) http://commonsware.com | http://github.com/commonsguy http://commonsware.com/blog | http://twitter.com/commonsguy Warescription: Three Android Books, Plus Updates, One Low Price! -- You received this message because you are subscribed to the Google Groups "Android Developers" group. To post to this group, send email to [email protected] To unsubscribe from this group, send email to [email protected] For more options, visit this group at http://groups.google.com/group/android-developers?hl=en

