Search code examples
javaandroidandroid-fragmentsfragmentpageradapter

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.


Solution

  • 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();
        }
    
    
    
    }
    

    Two fragments added four fragments added