Android fragment OnCreateView called twice
Asked Answered
I

1

6

I am using a FragmentPagerAdapter with fragments. My problem is that when I call setCurrentItem, the OnCreateView method of the fragment that is being loaded is called twice. It is important to note however that the fragment is not recreated, it is simply resumed. I am desperate to find a solution that causes OnCreateView to only be called once.

I have taken a look at the following questions and some more, but none of them contain answers for my case:

Android oncreateview called twice

OnCreateView called multiple times / Working with ActionBar and Fragments

Fragment onCreateView and onActivityCreated called twice

Most questions I found do not concern FragmentViewPagers, making them mostly unhelpful.

I would be very grateful for any help!

Irascible answered 11/7, 2015 at 8:32 Comment(0)
C
7

I am using a FragmentPagerAdapter with fragments. My problem is that when I call setCurrentItem, the OnCreateView method of the fragment that is being loaded is called twice. It is important to note however that the fragment is not recreated, it is simply resumed. I am desperate to find a solution that causes OnCreateView to only be called once.

It is not called twice. What you are experiencing is the default behavior of the ViewPager, which caches always at least one of its page (Fragment), depending of the value of setOffscreenPageLimit(int limit). So onCreateView is called once for each instance returned by getItem

Cosmonaut answered 11/7, 2015 at 8:41 Comment(4)
I don't quite understand what you're saying. Are you saying that when I switch to a page, it loads the fragment but also loads a cache version, hence oncreateview being called twice?Irascible
This strikes me as odd, because oncreateview is called twice whenever I switch to the fragment page, even if I have been only in the page adjacent to it. This would suggest that the viewpager creates a cached copy even when there is one available. If the cache is redundant, as this evidence seems to suggest, how can I rid myself of this behaviour?Irascible
Apparently it only calls it once if I am swiping from an adjacent fragment page. I'm making network requests in my oncreateview. Is there a way I can pass on the data responses of the visible fragment network requests to the cached version so these requests do not have to be done twice?Irascible
Not really. You probably want to think about a different approachCosmonaut

© 2022 - 2024 — McMap. All rights reserved.