3

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()?
Reza Bigdeli
  • 1,142
  • 1
  • 12
  • 25
  • No, You should change your ViewPagers offscreen page limit if You don't want to destroy the views. Otherwise You will violate Fragments lifecycle. See Fragments [`onDestroyView`](https://developer.android.com/reference/android/support/v4/app/Fragment#ondestroyview) method. – Pawel Nov 06 '18 at 13:40

1 Answers1

4

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.

Knossos
  • 15,802
  • 10
  • 54
  • 91
  • Well I'm not sure about the fragment being destroyed! since when you navigate from a fragment to somewhere and come back, `onCreateView` WON'T be called but `onViewCreated` will. And also what do you think about `onActivityCreated` – Reza Bigdeli Nov 07 '18 at 16:14
  • Do you have a [mcve]? I'd be interested to see what is happening directly. It is my expectation that `onViewCreated()` should only be called once after the view is created. However, I'll admit I am one of the people that prefers to take care of all of the UI in `onCreateView()`. -- As for `onActivityCreated()`, I would only use that for cases where I need guaranteed access to the `Activity` from the `Fragment`. It used to be that the best way to talk back, was to use an `Interface` with a callback. Once `onActivityCreated()` was called, you knew the activity was ready to be called upon. – Knossos Nov 09 '18 at 10:55
  • Yes well I think according to [this link](https://stackoverflow.com/a/12228442/3415152) it happens when a Fragment Transaction is used – Reza Bigdeli Nov 10 '18 at 06:04
  • @Knossos is there a chance that onViewCreated is overloaded and some stuff that happening there does not have enough time to get prepared properly and we need to use onViewCreated? Did you ever had an issue that to be solved onViewCreated was needed? – CDrosos Sep 07 '20 at 14:55