Add / Delete pages to ViewPager dynamically

I would like to add or delete pages from my view pager dynamically. Is that possible?

  • Memory efficient image resize in Android
  • Can't get WRITE_SETTINGS permission
  • PopupWindow above Virtual keyboard
  • How to animate text change in TextView?
  • Where is main() in Android?
  • How to get minimum Hardware requirement for android application
  • Android APK size limitation in Google Play
  • Set Holo theme in older Android versions?
  • How to determine if network type is 2G, 3G or 4G
  • How can I add a sub folder to the raw folder in my Android app?
  • reading android jpeg EXIF metadata from picture callback
  • Call javascript function in Android WebView
  • 7 Solutions collect form web for “Add / Delete pages to ViewPager dynamically”

    Yes, since ViewPager gets the child Views from a PagerAdapter, you can add new pages / delete pages on that, and call .notifyDataSetChanged() to reload it.

    Yes, the code should be like this:

    public int addPage(View view, int position) {
            if ((position >= 0) && (position < getSize())) {
                myPagerAdapter.mListViews.add(position, view);
                myPagerAdapter.notifyDataSetChanged();
                return position;
            } else {
                return -1;
            }
        }
    
    public View removePage(int position) {
            if ((position < 0) || (position >= getSize()) || (getSize()<=1)) {
                return null;
            } else {
                if (position == mPager.getCurrentItem()) {
                    if(position == (getSize()-1)) {
                        mPager.setCurrentItem(position-1);
                    } else if (position == 0){
                        mPager.setCurrentItem(1);
                    }
                }
                View tempView = myPagerAdapter.mListViews.remove(position);
                myPagerAdapter.notifyDataSetChanged();
                return tempView;
            }
        }
    

    But there is a bug. If the current Item is 0, and to remove page 0, it will not refresh the screen instantly, I haven’t found a solution for this.

    Yes. You can add or delete views dynamically to the PagerAdapter that is supplying them to the ViewPager and call notifyDataSetChanged() from the PagerAdapter to alert the affected ViewPager about the changes. However, when you do so, you must override the getItemPosition(Object) of the PagerAdapter, that tells them whether the items they are currently showing have changed positions. By default, this function is set to POSITION_UNCHANGED, so the ViewPager will not refresh immediately if you do not override this method. For example,

    public class mAdapter extends PagerAdapter {
        List<View> mlist;
    
        public void addView(View view, int index) {
            mList.add(index, view);
            notifyDataSetChanged();
        }
    
        public void removeView(int index) {
            mList.remove(index);
            notifyDataSetChanged();
        }
    
        @Override
        public int getItemPosition(Object object) {
            if (mList.contains((View) object) {
                return mList.indexOf((View) object);
            } else {
                return POSITION_NONE;
            }
        }
    }
    

    Although, if you simply want to add or remove the view temporarily from display, but not from the dataset of the PagerAdapter, try using setPrimaryItem(ViewGroup, int, Object) for going to a particular view in the PagerAdapter’s data and destroyItem(ViewGroup, int, Object) for removing a view from display.

    Here’s an alternative solution to this question. My adapter:

    private class PagerAdapter extends FragmentPagerAdapter implements 
                  ViewPager.OnPageChangeListener, TabListener {
    
        private List<Fragment> mFragments = new ArrayList<Fragment>();
        private ViewPager mPager;
        private ActionBar mActionBar;
    
        private Fragment mPrimaryItem;
    
        public PagerAdapter(FragmentManager fm, ViewPager vp, ActionBar ab) {
            super(fm);
            mPager = vp;
            mPager.setAdapter(this);
            mPager.setOnPageChangeListener(this);
            mActionBar = ab;
        }
    
        public void addTab(PartListFragment frag) {
            mFragments.add(frag);
            mActionBar.addTab(mActionBar.newTab().setTabListener(this).
                                setText(frag.getPartCategory()));
        }
    
        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }
    
        @Override
        public int getCount() {
            return mFragments.size();
        }
    
        /** (non-Javadoc)
         * @see android.support.v4.app.FragmentStatePagerAdapter#setPrimaryItem(android.view.ViewGroup, int, java.lang.Object)
         */
        @Override
        public void setPrimaryItem(ViewGroup container, int position,
                Object object) {
            super.setPrimaryItem(container, position, object);
            mPrimaryItem = (Fragment) object;
        }
    
        /** (non-Javadoc)
         * @see android.support.v4.view.PagerAdapter#getItemPosition(java.lang.Object)
         */
        @Override
        public int getItemPosition(Object object) {
            if (object == mPrimaryItem) {
                return POSITION_UNCHANGED;
            }
            return POSITION_NONE;
        }
    
        @Override
        public void onTabSelected(Tab tab, FragmentTransaction ft) {
            mPager.setCurrentItem(tab.getPosition());
        }
    
        @Override
        public void onTabUnselected(Tab tab, FragmentTransaction ft) { }
    
        @Override
        public void onTabReselected(Tab tab, FragmentTransaction ft) { }
    
        @Override
        public void onPageScrollStateChanged(int arg0) { }
    
        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) { }
    
        @Override
        public void onPageSelected(int position) {
            mActionBar.setSelectedNavigationItem(position);
        }
    
        /**
         * This method removes the pages from ViewPager
         */
        public void removePages() {
            mActionBar.removeAllTabs();
    
                        //call to ViewPage to remove the pages
            vp.removeAllViews();
            mFragments.clear();
    
            //make this to update the pager
            vp.setAdapter(null);
            vp.setAdapter(pagerAdapter);
        }
    }
    

    Code to remove and add dynamically

    //remove the pages. basically call to method removeAllViews from ViewPager
    pagerAdapter.removePages();
    
    pagerAdapter.addPage(pass your fragment);
    

    After the advice of Peri Hartman, it started to work after I set null to ViewPager adapter and put the adapter again after the views removed. Before this the page 0 doesn’t showed its list contents.

    I am sure you have created an adapter by extending PageAdapter, so there is one method:

     @Override
     public void destroyItem(View collection, int position, Object view) {
               ((ViewPager) collection).removeView((View) view);
     }
    

    For detailed example for the same, just go through this example.

    First:override the pagerAdapter method “getItemPosition”

    @Override
    public int getItemPosition(Object object) {
            return POSITION_NONE;
        }
    }
    

    Second:remove the data bind with the adapter.and call adapter.notifydatachanged

    @Bind(R.id.pager)
    ViewPager pager;
    int pos = pager.getCurrentItem();
    pager.removeViewAt(pos);
    
    Android Babe is a Google Android Fan, All about Android Phones, Android Wear, Android Dev and Android Games Apps and so on.