Monday 4 May 2015

FragmentStatePagerAdapter vs FragmentPagerAdapter

FragmentStatePagerAdapter

1. FragmentStatePagerAdapter destroy the fragment which is no longer needed i.e which is not visible to user.Similar to a recylerview/Listview which recyles the view memory      when goes out of sight.
2. FragmentStatePagerAdapter Saves the Fragment bundle from the SaveInstance and re-stores the fragment when user comes back to the destroyed fragment.

FragmentPagerAdapter

1. In FragmentPagerAdapter fragment of each page which user visited is kept in memory.Which causes memory issues in case of heavy fragments.
2. FragmentPagerAdapter calls detach(Fragment) on the transaction instead of remove(Fragment).This only removes the fragment view but fragment Instance remains in memory.


So, When to use FragmentPagerAdapter And FragmentStatePagerAdapter?

When we know the amount of data to be display or content is static or another case can when we know devices we are targetting never gonna run out of memory, Because this causes alot of memory consumption as it loads fragment in memory once visited by user.

And In case when we do not know the size, then we prefer FragmentStatePagerAdapter.Because it allows us adding fragments without causing memory issues.As it destroy the fragment which is no longer visible kinds of recyling the memory from those memory.

Code Snipnet for FragmentStatePagerAdapter:

class MyAdapter extends FragmentStatePagerAdapter {

        public MyAdapter(FragmentManager fm) {

            super(fm);

        }

        @Override

        public int getCount() {

            return NUM_ITEMS;

        }

        @Override

        public Fragment getItem(int position) {

            return new Fragment(params if any);

        }

    }



Code Snipnet for FragmentPagerAdapter:

class MyAdapter extends FragmentPagerAdapter {

        public MyAdapter(FragmentManager fm) {

            super(fm);

        }

        @Override

        public int getCount() {

            return NUM_ITEMS;

        }

        @Override

        public Fragment getItem(int position) {

            return new Fragment(params if any);

        }

    }





References Stackoverflow,http://developer.android.com/

No comments:

Post a Comment