Tonight, I put together a simple Android project to get a better grip on the Fragment lifecycle as it relates to the Activity lifecycle, and to do some simple Fragment manipulation. I have used Fragments in past projects, but never from scratch, and setting this up was pretty illuminating. I annotated the source with explanations and relevant Stack Overflow links and pushed the project up to GitHub. The resulting project now lies here: https://github.com/goat000/FragmentDemo
Some of my basic findings:
- You can’t remove Fragments that were declared within your Activity’s layout file. You can only remove Fragments that were added programmatically.
- If you are going to add a fragment programmatically, make sure to inflate its view with inflater.inflate(R.layout.test_fragment, container, false); If you skip the third parameter, you’ll get IllegalStateExceptions that say “The specified child already has a parent.” It’s rather annoying, as the stack trace won’t lead back into your code.
- onActivityCreated is called for a new Fragment even if its Activity was created a looong time ago, and it’s called after onAttach. This seems peculiar – how do we attach to an Activity before it’s created? However, it doesn’t seem to hurt anything.
- Fragments that are added programmatically are retained across configuration changes, like rotating the screen.
- Fragments have their own onSaveInstanceState but no onRestoreInstanceState. You can restore the saved Bandle in onCreate, onCreateView, or onActivityCreated.
Please do let me know if you run into problems with this.
One of my finding: in an activity, view states (e.g. a checkbox state) are restored in onRestoreInstanceState (e.g. the checkbox is checked again if it was already checked before a screen orientation). This means that if you want, for any reason, to uncheck or change the label of your component, you must do it after view state restoration. In an Activity, that would be by overriding onRestoreInstanceState()… But that does not exist in fragment! Which means that it gets either complicated or ugly to change a component state after an orientation change, as the old values before rotation will be restored and override any change made meanwhile in onCreateView()/onActivityCreated() (i.e. when you get your parameters back from the bundle and thus are tempted to set some values in your UI component)…
Sure there is not much reasons to do this but that means that we often restore a UI component state for nothing in onCreateView() (well except for the very first time a fragment is created :-D)…
Behold is a fine offering for victory. brianwilliammee.com
http://bit.ly/2Kwh8MR