Search code examples
androidandroid-viewpager

Android ViewPager and FragmentStatePagerAdapter - not started on first item


I have a View containing a list of items. When I click on a particular listitem, it shows the details of that particular object in a new activity (and a new fragment). That all works fine.

Now I wanted to add a function, that the user can swipe from selected in detail activity shown item to the next/previous item, so he doesn't have to go back to the list and choose another item. I tried using ViewPager and FragmentStatePagerAdapter and it works and really has nice effects.

My Activity.java:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_exercise);

        // Instantiate a ViewPager and a PagerAdapter.
        mPager = (ViewPager) findViewById(R.id.pager);
        mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
        mPager.setAdapter(mPagerAdapter);

    ...
    }

   private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
        public ScreenSlidePagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
        // pos is the position of the object in the list    
            Fragment fragment = ExerciseFragment.newInstance(exercisesArray, pos+position);
            return fragment;
        }

        @Override
        public int getCount() {
            return exercisesArray.size();
        }
    }

My questions:

  1. Is ViewPager the right way for my intention? Ever time the user swipes to next item, a new fragment is instantiated. The list can contain about 100 items... so maybe 100 fragments are created? Can this be a problem?

  2. My implementation only works fine, if the first item is selected and swiped. For example: I have 5 items in a list and the first one is clicked. Now I can swipe to second item, to third item, back to second. BUT if the user clicks on third item of the list, I can't swipe left to second and first item! Anyone have an idea?

Thanks a lot!


Solution

  • You dont need to load all the fragments upfront in your viewpager, for deciding the limit of the number of fragments you want to load upfront , use viewPager.setOffscreenPageLimit(yourDesiredIntegerValue); for more info, see this n


    Note: You can't set this limit to zero, but even if you try to set it, viewpager will ignore it and will set this limit to 1(default).

    And about the second question, keep your activity in the backstack, when your user will return back to that, the normal flow will follow.Its simple as that.