Search code examples
androidinfinite-carousel

ViewPager position remains same for different carousel images


I am working on Carousel View using FragmentPagerAdapter & ViewPager. I am facing issue that whenever i am changing image name on each page scrolling, only for second image wrong name is displaying. In this case it shows name of first image and from third image onwards again position is increasing from 0 to 1 & so on. I checked the position in onPageScrolled & it is showing 0 for both 1st & 2nd images. Also one more thing i have observed that call is not coming in getItem method only when second image displayed. So can you please guide me if you have any idea to solve this issue.


Solution

  • The ViewPager instantiates the fragments surrounding the current one in order to get a smooth swipe. Using setOffScreenPageLimit(int) you set the number of pages that should be retained to either side of the current page. The default is 1.

    1. When you set the ViewPager's adapter and it shows the first page (position=0), the fragment of the second page is also created(getItem()) while the current page position is still 0.
    2. You swipe to the page 2 and the third fragment is created while the current page position is 1.(Now there is one exisiting fragment instance to each side of the current one)
    3. swipe to page 3 and the fourth fragment is created showing the current page position, which is now 2. (page 1 fragment is destroyed)
    4. and so on...

    if you want to get the actual position of the different fragments, get it directly from the FragmentPagerAdapter.getItem(int position), setting the position as an argument of the fragment before returning it.

    public Fragment getItem(int position) {
        YourFragment fragment = new YourFragment();
        Bundle args = new Bundle();
        args.putInt("page_position", position);
        fragment.setArguments(args);
        return fragment;
    }
    

    Then, you can get the position in YourFragment like this:

    int position = getArguments().getInt("page_position"));