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
As Fragment is embedded inside an Activity, it will be killed when Activity is killed.
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.
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.
try:
yourViewPager.setOffscreenPageLimit(2)
where 2 is the amount of pages to keep in memory on either side of the current page.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With