50

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!

A_P
  • 331
  • 3
  • 15
Cabezas
  • 9,329
  • 7
  • 67
  • 69

3 Answers3

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.

Ryan M
  • 18,333
  • 31
  • 67
  • 74
M D
  • 47,665
  • 9
  • 93
  • 114
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

fada21
  • 3,188
  • 1
  • 22
  • 21
  • 3
    Simple links don't answer questions. For instance, in the lifecycle there's no mention of the createView. – Alberto M Dec 09 '20 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

Community
  • 1
  • 1
Don Chakkappan
  • 7,397
  • 5
  • 44
  • 59
  • 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 '19 at 02:19