Difference between onCreateView and onViewCreated

2019-01-04 10:19发布

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);
}

8条回答
贪生不怕死
2楼-- · 2019-01-04 10:39

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.

查看更多
Luminary・发光体
3楼-- · 2019-01-04 10:47

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 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 for onCreate().
And I'm happy with that.

查看更多
我命由我不由天
4楼-- · 2019-01-04 10:47

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 the onViewCreate . All other performance characteristics look the same.

查看更多
Animai°情兽
5楼-- · 2019-01-04 10:48

onCreateView returns the inflated view. OnViewCreated is called just after onCreateView and get has parameter the inflated view. Its return type is void

查看更多
地球回转人心会变
6楼-- · 2019-01-04 10:54

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.

查看更多
做自己的国王
7楼-- · 2019-01-04 11:01

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.

查看更多
登录 后发表回答