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 using findViewById in onCreateView.

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.

Leave a Comment