drew moore
drew moore

Reputation: 32680

Alternating the types of views displayed in a ViewPager

I'm building a magazine e-reader app, using a viewpager as the primary navigational element. Article objects are deserialized (from data received from a REST web service), and used to inflate "cover pages" that are inflated by the pager adapter, which the user "flips through".

This all works perfectly using a PagerAdapter with an instantiateItem method like this (with an ArrayList of articles passed to the adapter's constructor):

    @Override
    public Object instantiateItem(View arg0, int position) {

    final Article s = toShow.get(position);

    View v = getLayoutInflater().inflate(R.layout.previewpage, null);

    TextView hl = (TextView)v.findViewById(R.id.coverHl);
    ImageView img = (ImageView)v.findViewById(R.id.coverImg);

            ....

    hl.setText(s.title);
    img.setImageBitmap(s.image);

My issue is that, at every 6th position, I'd like to inflate a different view to show an ad. At the moment, I have an if statement added to the top of this method like :

if ((position != 0) && (position%6 == 0)){

after which I inflate the other view and place the appropriate ad on it. However, this leads to numerous complications: On the next view, I can no longer say toShow.get(position) because doing so skips one of the articles in the array (the one at the position at which the ad was shown). So, I created an int adsShown, which gets incremented every time an ad is shown, and call final Article s = toShow.get(position - adsShown). But when I do that, if the user flips back through the viewpager, an ArrayIndexOutOfBounds error is shown because it position-adsshown is -1.

I know I can figure out workarounds for these issues, but I'm questioning whether there is a simpler way to handle this task in the first place.

Any ideas?

Upvotes: 0

Views: 524

Answers (1)

ebarrenechea
ebarrenechea

Reputation: 3785

You can get the correct position using something like this:

// check if position > 0 to make sure we don't start with an ad
if(position > 0 && position%6 == 0) {
  // get ad view here
else {
  int index = position - (int)Math.floor(position/6);
  final Article s = toShow.get(index);
  ...
}

Also remember that your getCount will have to return the number of articles plus the number of ads or else it will not show all the articles you have in your array.

Upvotes: 1

Related Questions