Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using ViewPager with Fragments, the fragments are destroyed upon swipe

My application has a ViewPager whose adapter returns three Fragments. Each Fragment loads a list of data from Web in the onCreateView. So let's call these fragments A, B, C.

Once the activity containing the viewPager is open, Fragments A and B are loaded. But only A is visible now. So if I swipe to the right, then B is visible and C is loaded behind the scene. If I swipe to right again, then C is visible. The problem is that, fragment A's onDestroyView() is called and all its loaded data is gone! So if I come back to fragment A, then A's onCreateView() is called again and A's data is loaded from the web again.

Is it a default behaviour of ViewPager when using it with Fragment? Is it possible to keek the fragment alive (by not calling onDestroyView()) even while it is not visible?

Thanks

like image 741
user2062024 Avatar asked Jul 26 '13 20:07

user2062024


People also ask

Are fragments destroyed when activity is destroyed?

As Fragment is embedded inside an Activity, it will be killed when Activity is killed.

What does a ViewPager do?

ViewPager in Android allows the user to flip left and right through pages of data. In our android ViewPager application we'll implement a ViewPager that swipes through three views with different images and texts.

How do you get ViewPager fragments?

ViewPager save Fragment in FragmentManager with particular tags, So We can get ViewPager's fragment by FragmentManager class by providing tag. And ViewPager provide tag to each fragment by following syntax : Fragment page = getSupportFragmentManager(). findFragmentByTag("android:switcher:" + R.


1 Answers

try:

yourViewPager.setOffscreenPageLimit(2)

where 2 is the amount of pages to keep in memory on either side of the current page.

like image 72
Adam Johns Avatar answered Nov 01 '22 02:11

Adam Johns