简体   繁体   中英

How to add nextset of fragments without disturbing current fragments in FragmentPagerAdapter?

Here's the code to add the fragments for first time`

`if(mcursor==null) { items = (ArrayList) cnews.getItems(); mcursor = cnews.getNextPageToken();

        for (int i = 0; i < items.size(); i++) {

            Fragment cm = ContentFragment.newInstance(i, items.get(i).getTitle(),
                    items.get(i).getImageuri(), items.get(i).getDate(), items.get(i).getPublsher(), items.get(i).getDescription());
            frags.add(cm);

        }
        viewPager.setAdapter(new ContentfragmentAdapter(getSupportFragmentManager(), frags));

    }else{
        items = (ArrayList<News>) cnews.getItems();
        mcursor = cnews.getNextPageToken();
        for (int i = 0; i < items.size(); i++) {

            Fragment cm = ContentFragment.newInstance(i, items.get(i).getTitle(),
                    items.get(i).getImageuri(), items.get(i).getDate(), items.get(i).getPublsher(), items.get(i).getDescription());
            frags.add(cm);

        }

In else condition i want to add some more fragments after server call.How can i update the adapter without removing old fragments?

Please help me i am newbie in android development. Thanks in Adavance.

One of the crucial parts here is that you must call

notifyDataSetChanged()

on the adapter so that the underlying data structures are updated accordingly including triggering a redraw of the ViewPager. Also don't forget that getCount() must also return the expected number of elements (ie. no hardcoding values here)

public class SectionsPagerAdapter extends FragmentPagerAdapter {

    List<String> tagList;

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
        tagList = new ArrayList<>();

    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.

        return PlaceholderFragment.newInstance(tagList.get(position));
    }

    @Override
    public int getCount() {

        return tagList.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {

        return "SECTION "+(position+1);
    }

    public void add(int position, String key)
    {
        tagList.add(position, key);
        notifyDataSetChanged();
    }



}

添加了两个片段 添加了四个片段

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