简体   繁体   中英

How to add Fragment to the middle of FragmentStatePagerAdapter

I wanna add the Fragment to the middle of FragmentStatePagerAdapter with PagerSlidingTabStrip. But I can add the new Fragnent only in the end fo Adapter. Here is the code:

public class TabsPagerAdapter extends FragmentStatePagerAdapter {
    private ArrayList<String> TABS = new ArrayList<String>();

    public TabsPagerAdapter(FragmentManager fm) {
        super(fm);
        TABS.add("First");
        TABS.add("Second");
        TABS.add("Third");
    }


    @Override
    public Fragment getItem(int position) {
        return CardFragment.newInstance(position);
    }

    @Override
    public Parcelable saveState() {
        return super.saveState();
    }

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


    @Override
    public String getPageTitle(int position) {
        return TABS.get(position);
    }


}

Here is where I add new Fragment

adapter.TABS.add(1, "ffff");

adapter.notifyDataSetChanged();

int k = viewPager.getCurrentItem();
viewPager.setCurrentItem(k + 1);

pagerSlidingTabStrip.notifyDataSetChanged();

I face the similar problem, I solve it by invoke setAdapter() again before setCurrentItem , otherwise it will never update until the list scroll to index middleIndex+2:

viewPager.setAdapter(adapter);
viewPager.setCurrentItem(middleIndex);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM