问题
Currently (Android API 17), the only mention of super in the Android Reference on Fragment is casually via some code examples (unlike the Android Reference on Activity, which carefully notes where super is required).
SO suggests searching the web as needed, or waiting for a crash, to identify where a call to super is required. I'm asking SO users to share their knowledge on which of the Fragment lifecycle methods require a call to super.
Fragment lifecycle methods - require call to super
onAttach()onCreate()- presumably yes, asActivityversion requires itonCreateView()- seems ok with or withoutonActivityCreated()onViewStateRestored()onStart()- presumably yes, asActivityversion requires itonResume()- presumably yes, asActivityversion requires itonPause()- presumably yes, asActivityversion requires itonStop()- presumably yes, asActivityversion requires itonDestroyView()onDestroy()- presumably yes, asActivityversion requires itonDetach()onSaveInstanceState()- presumably yes, asActivityversion requires it
回答1:
All of the corresponding Activity lifecycle methods except onSaveInstanceState require calls to super. In addition:
onAttach()- yesonActivityCreated()- yesonViewStateRestored()- is not a Fragment methodonDestroyView()- yesonDetach()- yesonSaveInstanceState()- from Fragment#onSaveInstanceState it looks like a no
All of the methods that require calls to super share the first line of their method in android.app.Fragment:
mCalled = true;
That way the FragmentManager can check if mCalled is true and throw a SuperNotCalledException when it is not called. See FragmentManager#moveToState to see this implementation.
回答2:
When generating a fragment with Eclipse, the onCreateView method template code does not have a call to super.onCreateView. Also, the generally quite good book published by WROX: Android 4 Application Development misses it out in its sample lifetime code (it does not miss out any other calls to super).
Of course both these two sources could be incorrect, but using the Eclipse template and not adding super.onCreateView has not caused me an issue.
回答3:
I am typing with capital letter 'O' instead of small letter 'o'
means : OnCreate instead of onCreate methods.
Its a silly mistake but need to remember :)
Thanks
来源:https://stackoverflow.com/questions/14532182/which-android-fragment-lifecycle-methods-require-super