MehDi
MehDi

Reputation: 514

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

Upvotes: 1

Views: 1575

Answers (2)

Paresh
Paresh

Reputation: 6857

notifyDataSetChanged() will only Notify any registered observers that the data set has changed regardless of touching viewPager positions.

There are two different classes of data change events, item changes and structural changes. Item changes are when a single item has its data updated but no positional changes have occurred. Structural changes are when items are inserted, removed or moved within the data set.

You have to set viewPager's position to start page(position 0) manually after notifyDataSetChanged().

adapter.notifyDataSetChanged();
viewPager.setCurrentItem(0);

Upvotes: 1

Nithinlal
Nithinlal

Reputation: 5061

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);

Upvotes: 2

Related Questions