I want to implement this:
I use a ViewPager with a FragmentStatePagerAdapter.
I started with the example from this page:
http://developer.android.com/reference/android/support/v4/app/FragmentStatePagerAdapter.html
This is my ViewPager adapter:
public static class MyAdapter extends FragmentStatePagerAdapter { public MyAdapter(FragmentManager fm) { super(fm); } @Override public int getCount() { return NUM_ITEMS; } @Override public Fragment getItem(int position) { return ArrayListFragment.newInstance(position); } @Override public void destroyItem(ViewGroup container, int position, Object object) { super.destroyItem(container, position, object); } }
Every page of my ViewPager contains a ListView with some data. At the moment when I switch to a new page in ViewPager it will increase the RAM memory very quickly.
How should I remove the old fragments ?
I also used this but it does nothing:
public void destroyItem(ViewGroup container, int position, Object object) { FragmentManager manager = ((Fragment) object).getFragmentManager(); FragmentTransaction trans = manager.beginTransaction(); trans.remove((Fragment) object); trans.commit(); super.destroyItem(container, position, object); }
There is also a 1-2 seconds delay after I switch quickly to a new page or old page. Is there any technique to remove that delay. If I switch to a new page and wait for 2 second then on next switch there is no more delay.
Tested on Nexus 7.
You should not try to interfere with how Android manages your Fragment
implementations. The default for the setOffScreenPageLimit
should already be one. This means that Android will destroy old fragments when memory runs low. As long as you do not have a memory issue, just leave it be.
The reason why your memory increases is because Android keeps Fragment
instances in memory to be able to reconnect to them instead of having to instantiate them. I recommend you account for the contingency of your Fragment
instances being destroyed by the OS, saving their state if that happens, and let the OS do its job.
The delay you are experiencing could be due to some intensive computation on the UI thread. If it is, I suggest moving that out to, for example, an AsyncTask
. Without the code it is, however, just a guess as to what might cause the issue. But there being only an initial delay suggests that you are loading something which might block the UI thread.
Update: Have a look at https://stackoverflow.com/a/9646622/170781 which outlines very neatly how the ViewPager
handles Fragment
instances.
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