What's the essential difference between these two methods? When I create a TextView, should I use one over the other for performance?
Edit: What's the difference from
onCreateView() {
root = some view
View v = new View(some context);
root.add(v);
return root;
}
onViewCreated() {
View v = new View(some context);
getView().add(v);
}
We face some crashes initializing view in
onCreateView
.Because sometimes view is not properly initialized. So always use
findViewById
inonViewCreated
(when view is fully created) and it also passes the view as parameter.onViewCreated
is a make sure that view is fully created.onCreateView()
is the Fragment equivalent ofonCreate()
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 actually is an
onCreate()
method in Framents, 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 foronCreate()
.And I'm happy with that.
The main reason I would use
onViewCreated
is since it separates any initialization logic from the view hierarchy inflation/creation logic which should go in theonViewCreate
. All other performance characteristics look the same.onCreateView
returns the inflated view.OnViewCreated
is called just afteronCreateView
and get has parameter the inflated view. Its return type isvoid
i think the main different between these is when you use kotlin.in onCreateView() every Time you want to access to view in your xml file you should use findViewById but in onViewCreated you can simply access to your view just by calling the id of it.
onCreateView is used in fragment to create layout and inflate view. onViewCreated is used to reference the view created by above method. Lastly it is a good practice to define action listener in onActivityCreated.