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()
andonViewCreated
right? - Is it right to use
onActivityCreated
for initiating views, since it is called only once and it is called afteronCreateView()
?
You should inflate your
View
inonCreateView()
.Then you should setup your
View
inonViewCreated()
. Though, a lot of people will just set up theirView
inonCreateView()
after inflating it.If that function is being called multiple times, then the
Fragment
itself was destroyed and needs to be rebuilt.