The first part of your problem is detecting when the page changes. You can set the ViewPager
's OnPageChangeListener
using pager.setOnPageChangeListener()
. Within the OnPageChangeListener
that you create, you'll want to override the onPageChanged
method and put your logic into there. See this for reference: https://stackoverflow.com/a/11797936/3081611
The second part of your problem is how to send logic to the fragment itself. So you need some reference to the fragment. You can get the index of the fragment from the onPageChanged method. However, it doesn't actually return the fragment to you -- only the position. Getting the actual fragment is a little tricky. You can't use the pager's getItem
function. It's a bit misldeading, but getItem()
is what the ViewPager
uses to create a new fragment. If you try to use it, you're just going to get the reference to a new ScreenSlidePageFragment
that's not actually shown on screen.
A good way to get around this is to extend the ViewPager
and make your own custom pager that overrides the instantiateItem()
and destroyItem()
functions so that when a fragment is created or destroyed, it gets stored in an array. Then you can make a function that returns the actual fragment from the array. See this for reference: https://stackoverflow.com/a/15261142/3081611