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.
The difference is that you can use Fragments inside a FragmentPageAdapter . If you want to have fragments that are going to be used in other parts of your code this is your Adapter. Otherwise if you only want to have code that isn't going to be reused, you can use PagerAdapter .
This method may be called by the ViewPager to obtain a title string to describe the specified page. This method is deprecated. This method should be called by the application if the data backing this adapter has changed and associated views should update.
Using the ViewPager. OnPageChangeListener is the correct way to go, but you will need to refactor your adapter a bit in order to keep a reference to each Fragment contained in the FragmentPagerAdapter. Then, instead of creating a new Fragment, use the one contained in the adapter: mViewPager.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With