I would like to add or delete pages from my view pager dynamically. Is that possible?
you have to set the adapter to viewpager again, then it will refresh the content.
removeView(int pos) in my PagerAdaper
public void removeView(int index) {
imageFileNames.remove(index);
notifyDataSetChanged();
}
wherever I am removing the file I have to do like this
imagePagerAdapter.removeView(currentPosition);
viewPager.setAdapter(imagePagerAdapter);
EDIT:
This below method is effective, you can apply the below one.
public void updateView(int pos){
viewPager.setAdapter(null);
imagePagerAdapter =new ImagePagerAdapter(YOUR_CONTEXT,YOUR_CONTENT);
viewPager.setAdapter(imagePagerAdapter);
viewPager.setCurrentItem(pos);
}
replace YOUR_CONTEXT with your context and your content with your content name i.e. updated list or something.
@Bind(R.id.pager)
ViewPager pager;
int pos = pager.getCurrentItem();
pager.removeViewAt(pos);
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.