Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add / Delete pages to ViewPager dynamically

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

like image 874
Arnab Chakraborty Avatar asked Nov 09 '11 05:11

Arnab Chakraborty


2 Answers

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(object) {             return mList.indexOf(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.

like image 152
CodePro_NotYet Avatar answered Oct 12 '22 02:10

CodePro_NotYet


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.

like image 43
Zsombor Erdődy-Nagy Avatar answered Oct 12 '22 03:10

Zsombor Erdődy-Nagy