I would like to add or delete pages from my view pager dynamically. Is that possible?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With