问题
Is there any way for me to invoke a callback when the user swipes from one pane to the next? As far as my experimentation has revealed, the present (primary) pane/fragment as well as the adjacent two (to the left and right) are all 'resumed', so none of the regular fragment lifecycle callbacks are invoked. I'm interested in this in order to hide a MediaController as soon as the pane it's associated with has been left.
回答1:
You can attach an OnPageChangeListener
to your ViewPager to get updates on when the user swipes to a new page:
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageScrollStateChanged(int state)
{
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{
}
@Override
public void onPageSelected(int position)
{
Log.d("MainActivity", "New position = " + position);
}
});
And if you use a FragmentPagerAdapter
, your ViewPager's pages will be cached in memory. If you use a FragmentStatePagerAdapter
, they will not be cached.
回答2:
the Fragment's setUserVisibleHint()
would be callback as long as a fragment was completely disappeared or appeared, hide or show the MediaController operation can be done here.
public class YourFragment extend android.support.v4.app.Fragment {
...
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
System.out.println("VISIBLE");
} else {
System.out.println("GONE");
}
}
...
}
来源:https://stackoverflow.com/questions/24846349/callback-for-viewpager-transition-to-next-pane