49

I don't know when to use onCreate() or onCreateView().

I have used onCreate() and onCreateView() lifecycle methods. I think onCreate() for Activity and onCreateView() for Fragment. But I am not sure. Can I use onCreate() LifeCycle method in Fragment? I hope somebody can help me!

3

3 Answers 3

83

onCreate is called on initial creation of the fragment. You do your non graphical initializations here. It finishes even before the layout is inflated and the fragment is visible.

onCreateView is called to inflate the layout of the fragment i.e graphical initialization usually takes place here. It is always called some time after the onCreate method.

0
8

Activity lifecycle explained - http://developer.android.com/reference/android/app/Activity.html

Fragment lifecycle explained - http://developer.android.com/guide/components/fragments.html#Creating

Detailed lifecycle diagram - https://github.com/xxv/android-lifecycle

1
  • 3
    Simple links don't answer questions. For instance, in the lifecycle there's no mention of the createView.
    – Alberto M
    Dec 9, 2020 at 11:57
0

From documents :

onCreate

Called when the activity is starting.

This is where most initialization should go: calling setContentView(int) to inflate the activity's UI, using findViewById(int) to programmatically interact with widgets in the UI, calling managedQuery(android.net.Uri, String[], String, String[], String) to retrieve cursors for data being displayed, etc.

You can call finish() from within this function, in which case onDestroy() will be immediately called without any of the rest of the activity lifecycle (onStart(), onResume(), onPause(), etc) executing.

Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.

Link to documentation of onCreate

onCreateView

Called to have the fragment instantiate its user interface view. This is optional, and non-graphical fragments can return null (which is the default implementation). This will be called between onCreate(Bundle) and onActivityCreated(Bundle).

If you return a View from here, you will later be called in onDestroyView() when the view is being released.

Link to documentation of onCreateView

1
  • 12
    This doesn't answering the question as the onCreate() described is for Activity. The reason is simply because question is asking about Fragment. Not to mention, Fragment does not have setContentView() method.
    – Wei
    Feb 27, 2019 at 2:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.