14

I am trying to develop an app which will display numbers 1-10 and along with it a sound for that number.

Using the example in mobile.tutsplus for horizontal swiping, I have reached to a stage where all the numbers are displayed correctly but sound for 1 will not come when we go back from 2. (It comes initially when my activity starts with 1). Nor will it come for 10.

After solving the previous problem where sounds for 1 and 2 would come at once, I now understand that instantiateItem() will be called to pre-fetch the next entry.

I want to know at what point should I play the sound? Currently it is done in instantiateItem() which is why I don't hear it for 1 and 10. I thought I could do it in finishUpdate() but I see it's getting called multiple times.

As per the training guide, for such a collection of objects FragmentStatePagerAdapter should be used and I will be trying to move to that. But I would really like to get this to work correctly.

As you'd have guessed I'm a newbie and this is my first app. I could paste the code if required.

Nikhil
  • 143
  • 1
  • 1
  • 5

1 Answers1

18

ViewPager has a setOnPageChangeListener() method that will allow you to set an object that gets a callback when a new page becomes the one the user is looking at.

something like this will get you on the right path:

mPageChangeListener = new OnPageChangeListener() {

    @Override
    public void onPageScrollStateChanged(int arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onPageSelected(int pos) {
        playSoundForPage(pos);
    }

};
yourViewPager.addOnPageChangeListener(mPageChangeListener);

however you'll have to put this in whatever owns your ViewPager (activity, or fragment) and not your Adapter.

Community
  • 1
  • 1
FoamyGuy
  • 46,603
  • 18
  • 125
  • 156
  • Thanks a lot. I was suspecting setOnPageChangeListener() to be the one, but was not sure how to use it in the Adapter. Will try your method. – Nikhil Feb 22 '13 at 03:41
  • 3
    Did it a little differently.. private class MyPagerAdapter extends PagerAdapter implements ViewPager.OnPageChangeListener. Thanks again for your help. – Nikhil Feb 22 '13 at 04:42
  • 2
    `setOnPageChangeListener` is deprecated. Use `addOnPageChangeListener` instead. – Flimm Aug 01 '16 at 17:18