Search code examples
android-fragmentsandroid-viewpagerfragmentstatepageradapter

ViewPager with listviews and fragmentstatepageradapter


I have a viewpager with 5 tabs. In each fragment in the viewpager I have a listview that populated with data that I'm getting from server (server calls are done with AsyncTask).

I'm also using Fragmentstatepageradapter to have the most smoothly navigation possible, but it seems that something isn't working as it should when I'm navigating from a fragment that has a listview to another one with listview.

I'm wondering why, since the data is already stored and I want the viewpager to pop this fragments from the stack.

Here's my adapter:

public class TabsPagerAdapter extends FragmentStatePagerAdapter {

    public TabsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int index) {
        switch (index){
            case 0:
               return new Fragment1();
            case 1:
                return new Fragment2();
            case 2:
                return new Fragment3();
            case 3:
                return new Fragment4();
            case 4:
                return new Fragment5();
        }
        return null;
    }

    @Override
    public int getCount() {
        return 5;
    }
}

After a little research I've seen that getItem() should always returns a new instance of the fragment, but I'm still unable to store/restore states smoothly. I've tried using myViewPager.setOffscreenPageLimit(4); which gives better performance but the tabs navigation are still bit laggy.

Do I have to override instantiateItem/destroyItem in order to save fragment states?


Solution

  • Problem solved by changing the layout_height param of the ListView from wrap_content to match_parent.

    If the height set to wrap_content the getView method inside the adapter will be called multiple times, and thats the cause of the slow navigation between tabs.

    I hope this will help someone, answer found here.