Search code examples
androidandroid-fragmentsandroid-viewpagerfragmentpageradapter

FragmentPagerAdapter doesn't start position from 0 after call notifyDataSetChanged


I have a simple FragmentPagerAdapter class

    public class SectionsPagerAdapter extends FragmentPagerAdapter {

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

    @Override
    public Fragment getItem(int position) {
        PagerAdapter fragment;
                fragment = new PagerAdapter(data.get(position));

        return fragment;
    }


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

    @Override
    public CharSequence getPageTitle(int position) {
        if (position >= pageCount || position < 0)
            return null;
        return "Profile " + position;
    }

}

that PagerAdapter is a simple class that extends from Fragment. and then I set an instance of SectionsPagerAdapter to my ViewPager.

problem is here:

at first I have one page on view pager( data size is 1), when I get more data , I call SectionsPagerAdapter instance notifyDataSetChanged, but in getItem(int position) method instead of position start form 0, it start from 1 !!!

what should I do? I wanna re creat my view pager after I get more data Thanks in advance


Solution

  • You needed to set the adapter again to reset the position, notifyDataSetChanged is used to notify the adapter there is a data change so its rebind the data only.

    Or You can use this code to move the view pager which position you want

    viewPager.setCurrentItem(0);