September 4, 2012
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.