Where to initiate views in Fragment? onViewCreated or onActivityCreated

3.6k Views Asked by At

So where is the best place to initiate views in a fragment? We know that we should only inflate a layout inside onCreate() and not initiate views, like setting listeners.

You should inflate your layout in onCreateView but shouldn't initialize other views using findViewById in onCreateView.

And we know that onViewCreated() is called immediately after onCreateView() and basically the view is inflated and everything is ready. But the problem is that onViewCreated is called every time you go to another page and come back! So if you initiate your views here, for example add some listeners, since onViewCreated is called multiple times you end up initiating your views multiple time.

So my questions are:

  • Am I understanding onCreateView() and onViewCreated right?
  • Is it right to use onActivityCreated for initiating views, since it is called only once and it is called after onCreateView()?
1

There are 1 best solutions below

4
On

You should inflate your View in onCreateView().

Then you should setup your View in onViewCreated(). Though, a lot of people will just set up their View in onCreateView() after inflating it.

If that function is being called multiple times, then the Fragment itself was destroyed and needs to be rebuilt.