I've been working with the adapter that is showed at dynamically add and remove view to viewpager, but not all is working fine.
My ViewPager contains some custom views with webViews. What I've done is a extending class of PagerAdapter that implements almost the same methods that are showed in the answer that I first post.
The problem comes when I remove try to remove more than one page at the same time. As it's explained on the answer above, for deleting pages we set the adapter null and then we set it again. The method that I use it's almost the same than for only one page, but any page is removed.
Below is my code.
public void removeView(int position){
synchronized (mLock) {
int readingPosition = pager.getCurrentItem();
pager.setAdapter (null);
mInView.remove(position);
pager.setAdapter (this);
if(mInView.size() > 0){
if(readingPosition > position){
pager.setCurrentItem(readingPosition-1);
}else if(readingPosition < position){
pager.setCurrentItem(readingPosition);
}else if(readingPosition == position){
pager.setCurrentItem(0);
}
}
}
}
public void removeViews (ArrayList<Integer> positions){
synchronized (mLock) {
int readingPosition = pager.getCurrentItem();
Flyer readingFlyer = null;
if(!positions.contains(readingPosition)){
readingFlyer = mInView.get(readingPosition);
}
pager.setAdapter (null);
for(int i = 0; i < positions.size(); i++){
mInView.remove(positions.get(i));
}
pager.setAdapter (this);
if(!positions.contains(readingPosition)){
pager.setCurrentItem(mInView.indexOf(readingFlyer));
}else if(mInView.size() > 0){
pager.setCurrentItem(0);
}
}
}
Why it's not working if it's almost the same?
I've been trying to put notifyDataSetChanged()
above and below setAdapter(this)
but it didn't work.
Also, I've tried to not set the adapter again as it's shown at Add / Delete pages to ViewPager dynamically, I think that only calling notifyDataSetChanged()
should work, but it don't.
I've finally solved this annoying error changing a bit the method.
I discovered that when I was calling .remove(positions.get(i))
or simply .remove(positions.get(0))
any page was removed, so I suposed that the problem was on the use of .remove()
and then I found Why ArrayList.remove is not working, that it's not the same problem but show me another way to do the same.
Here my final code, maybe it's useful for someone.
public void removeViews (final ArrayList<Integer> positions){
synchronized (mLock) {
int readingPosition = pager.getCurrentItem();
Flyer readingFlyer = null;
if(!positions.contains(readingPosition)){
readingFlyer = mInView.get(readingPosition);
}
pager.setAdapter (null);
List<Flyer> mToRemove = new ArrayList<Flyer>();
for(int i = 0; i < positions.size(); i++){
mToRemove.add(mInView.get(positions.get(i)));
}
mInView.removeAll(mToRemove);
pager.setAdapter (this);
if(!positions.contains(readingPosition)){
pager.setCurrentItem(mInView.indexOf(readingFlyer));
}else if(mInView.size() > 0){
pager.setCurrentItem(0);
}
}
}