For View
s having IDs, they will be auto-saved when calling super.onSaveInstanceState(outState);
.
For Fragment
s added to an Activity
, what are the cases that it will be re-created when its Activity
is re-created (eg screen rotation), and what are the cases it will not? What to determine? What is the rule?
So far, i have tried the following cases. But trial-n-error does not mean any rules or solutions.
Cases when Fragment
s are re-stored:
FragmentTransaction.add()
to the layout with an ID. FragmentTransaction.add()
to a tag only Cases when Fragment
s are NOT re-stored:
super.onSaveInstanceState(outState);
is skipped. Fragment
s in a UI without a matching ID. What is the general rule? Anything i missed in the documentation?
Thanks in advance.
To my understanding, and experiments, ALL dynamically (programmatically) added Fragment
s are saved upon their Activity
calling super.onSaveInstanceState(outState)
.
Fragment
s includes,
Fragment
s with only a tag (no UI), Fragment
s attached to a View
(with UI), Fragment
s with both an UI and a tag. Regarding restoring a Fragment
with an UI into a layout that with no matching ID, the Fragment
is indeed re-created. It just cannot be shown visually in the layout, with the following warning message:
04-08 11:41:22.445: W/PhoneWindow(9853): Previously focused view reported id 2131165226 during save, but can't be found during restore.
Once we are back into an UI with its matching ID, it will be restored correctly.
I had the same problem, you can see it here: After screen rotation, findFragmentById() returns a fragment, even if there's no such ID inside the layout
The Android Developer Documentation at http://developer.android.com/training/basics/fragments/communicating.html quotes this:
When a configuration change causes the activity hosting these fragments to restart, its new instance may use a different layout that doesn't include the same fragments as the previous layout. In this case all of the previous fragments will still be instantiated and running in the new instance. However, any that are no longer associated with a tag in the view hierarchy will not have their content view created and will return false from isInLayout(). (The code here also shows how you can determine if a fragment placed in a container is no longer running in a layout with that container and avoid creating its view hierarchy in that case.)
That means, we have to check screen orientation than believing in null pointer checks.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.