I have simple PagerAdapter:
public class MyAdapter extends PagerAdapter {
Context context;
int[] res;
LayoutInflater inflater;
public MyAdapter(Context context, int[] res) {
this.context = context;
this.res = res;
}
@Override
public int getCount() {
return res.length;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView res1;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View item = inflater.inflate(R.layout.my_item, container,
false);
res1 = (ImageView) item.findViewById(R.id.res1);
res1.setImageResource(res[position]);
imageViewWhichIsDefinedOutsideViewPagerItem.setImageResource(res[position]);
((ViewPager) container).addView(item);
return item;
}
}
The problem is when I'm setting ImageViews like this:
res1.setImageResource(res[position]);
imageViewWhichIsDefinedOutsideViewPagerItem.setImageResource(res[position]);
res1 which is inflated to ViewPager has a good resource image but imageViewWhichIsDefinedOutsideViewPagerItem has a different resource. How is that possible if I am setting res[position] for both of them? Why is this happening?
instantiateItem()
is called when a page is instantiated, not when a page is shown. Pages are created before they are shown, so that the animation can be smooth as the user swipes between pages.Do not do anything in
instantiateItem()
that affects widgets outside of that individual page.If you want to change
imageViewWhichIsDefinedOutsideViewPagerItem
when the page changes, set up anOnPageChangedListener
and do the work there.