Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I tell my custom FragmentPagerAdapter to stop destroying my fragments?

I have a ViewPager with a FragmentPagerAdapter, and my app has previously used just two fragments (different types) without issues.

I just added a third fragment, though, and now my adapter/viewpager seems to be destroying my fragments when I get far away from them. For example, if I'm on page 1, page 3 is destroyed and recreated when I get close to it. If I'm on page 3, the same happens to page 1.

This is causing lots of issues in my app. The fragments aren't very RAM-heavy at all, so how can I stop this from happening?

like image 901
Steven Schoen Avatar asked Nov 07 '12 15:11

Steven Schoen


2 Answers

I believe you are looking for ViewPager.setOffscreenPageLimit().

In your case, the following should keep your fragments in memory and not destroy them.

ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
pager.setOffscreenPageLimit(2);

However, I suspect that you are not correctly storing your view state when being destroyed. Your fragments should correctly handle being destroyed/recreated. Your fragments would for example also be destroyed and recreated if an orientation change happens. It could also happen if the user leaves your application and the system later needs memory and destroys your Activity. It should be able to reopen and be in the same state as before. If this is indeed the problem for you, consider saving state in onSaveInstanceState(). The saved state will be presented to you in onCreate where you can initialize the state of the fragment to be the same as the destroyed one.

like image 179
foens Avatar answered Nov 19 '22 08:11

foens


just override this method in FragmentpagerAdapter

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
       // TODO Auto-generated method stub
       super.destroyItem(ViewGroup container, int position, Object object);
}

remove super.destroyItem(ViewGroup container, int position, Object object);

from your code

like image 5
Jinu Avatar answered Nov 19 '22 08:11

Jinu