Difference between onCreateView and onViewCreated in Fragment
We face some crashes initializing view in onCreateView
.
You should inflate your layout in
onCreateView
but shouldn't initialize other views usingfindViewById
inonCreateView
.
Because sometimes view is not properly initialized. So always use findViewById
in onViewCreated
(when view is fully created) and it also passes the view as parameter.
onViewCreated
is a make sure that view is fully created.
onViewCreated android Documentation
Called immediately after onCreateView
(android.view.LayoutInflater, android.view.ViewGroup
, android.os.Bundle
) has returned, but before any saved state has been restored in to the view. This gives subclasses a chance to initialize themselves once they know their view hierarchy has been completely created. The fragment's view hierarchy is not however attached to its parent at this point.
onViewCreated
is called immediately after onCreateView
(the method you initialize and create all your objects, including your TextView
), so it's not a matter of performance.
From the developer site:
onViewCreated(View view, Bundle savedInstanceState)
Called immediately after onCreateView(LayoutInflater, ViewGroup, Bundle) has returned, but before any saved state has been restored in to the view. This gives subclasses a chance to initialize themselves once they know their view hierarchy has been completely created. The fragment's view hierarchy is not however attached to its parent at this point.
Source: Fragment#onViewCreated
It's better to do any assignment of subviews to fields in onViewCreated
. This is because the framework does an automatic null check for you to ensure that your Fragment's view hierarchy has been created and inflated (if using an XML layout file) properly.
Code snippet from: FragmentManger.java
// This calls onCreateView()
f.mView = f.performCreateView(f.getLayoutInflater(f.mSavedFragmentState), null, f.mSavedFragmentState);
// Null check avoids possible NPEs in onViewCreated
// It's also safe to call getView() during or after onViewCreated()
if (f.mView != null) {
f.mView.setSaveFromParentEnabled(false);
if (f.mHidden) f.mView.setVisibility(View.GONE);
f.onViewCreated(f.mView, f.mSavedFragmentState);
}
onCreateView()
is the Fragment equivalent of onCreate()
for Activities and runs during the View creation.onViewCreated()
runs after the View has been created.
should I use one over the other for performance?
NO. There's no evidence of a performance boost.
There is actually an onCreate()
method in Fragments too, but it's rarely used (I do never use it, nor find a good use case for it).
I always use onCreateView()
in Fragments as a replacement for onCreate()
.
And I'm happy with that.