Reputation: 3731
I have a requirement to show a ViewPager displaying initially just one View.
Once this View goes through measure & layout pass, depending on the result of these I might need to change the contents of the adapter.
While doing so, I've come across a scenario where the ViewPager will not follow through with it's movement while trying to swipe to the next item from a certain position.
I'm sure I'm doing something wrong in my adapter implementation, yet I can't point my finger at the problem.
For the sake of demonstration I've created a dummy adapter that will mimic what happens on my actual project. In order to reproduce the issue just try to swipe all the way to position 2 (3rd item), result is you can't get past position 1 (2nd item).
Thanks!
public class CustomAdapter extends PagerAdapter {
int pages = 0;
@Override
public int getCount() {
return pages;
}
@Override
public boolean isViewFromObject(View view, Object o) {
return view == o;
}
public void setPages(int x) {
this.pages = x;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
TextView tv = new TextView(MainActivity.this);
ViewGroup.LayoutParams lp =
new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(lp);
tv.setText("Position: " + position);
if (position == 0 && pages == 1) {
setPages(2);
notifyDataSetChanged();
}
if (position == 1 && pages == 2) {
setPages(3);
notifyDataSetChanged();
}
container.addView(tv);
return tv;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
Activity (onCreate or so):
CustomAdapter adapter = new CustomAdapter();
adapter.setPages(1);
vp.setAdapter(adapter);
adapter.notifyDataSetChanged();
Upvotes: 2
Views: 1272
Reputation: 3705
instantiateItem item method is wrong place to do it. because it doest work for only one view it works for 3 view at same time.
try moving
if (position == 0 && pages == 1) {
setPages(2);
notifyDataSetChanged();
}
if (position == 1 && pages == 2) {
setPages(3);
notifyDataSetChanged();
}
in
setPrimaryItem
Method
UPDATE:
Try to call instantiateItem
method for the position you want in the setPrimaryItem
method. You can do it since instantiateItem
is a public
method.But i have no idea how it is going to work it is a theory. Just give it a try.
Upvotes: 2