Add / Delete pages to ViewPager dynamically
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(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.