如何设置setOnPageChangeListener?

时间:2013-06-11 18:40:22

标签: android fragment

我在FragmentActivity中创建并设置了Fragment,如下所示:

public class PosFragmentActivity extends FragmentActivity {
    ...
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_main);
        ...
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()
                , numOfPositionsForClass);
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);
        ...
    }
...
}

如何添加setOnPageChangeListener所以当滚动Tab / Fragment / Page时,它会调用方法?

3 个答案:

答案 0 :(得分:7)

pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
     @Override
     public void onPageSelected(int position) 
     {     
     }
     @Override
     public void onPageScrollStateChanged(int state)
     {
     }
     @Override
     public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
     {
     }
});

答案 1 :(得分:1)

在ViewPager对象上设置侦听器。

这是通过ViewPager.setOnPageChangeListener方法完成的。

您可以实施自己的ViewPager.OnPageChangedListener

继承提供的ViewPager.SimpleOnPageChangeListener

Example:
mViewPager.setOnPageChangeListener( new ViewPager.SimpleOnPageChangeListener() );

答案 2 :(得分:1)

现在不推荐使用setOnPageChangeListener,因此请改用:

ViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });