Callback for ViewPager transition to next pane?

纵然是瞬间 提交于 2019-12-24 11:15:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!