从未到过OnPageSelected,如何获取片段中的当前可见页面?

时间:2014-02-21 13:31:44

标签: java android android-viewpager fragmentstatepageradapter

我尝试将界面放在我的Activity,我的片段和FragmentStatePagerAdapter中。但在所有这些代码中,代码永远不会到达那里。这就是我的FragmentStatePagerAdapter的样子,因为这是我最近的尝试。

FragmentStatePagerAdapter:

public static class AppSectionsPagerAdapter extends FragmentStatePagerAdapter implements 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 arg0)
    {
        // TODO Auto-generated method stub
        Log.w("onpage", "onpage executed");
        currentSelectedFragmentPosition = arg0;
    }

    public int getCurrentSelectedFragmentPosition()
    {
        return currentSelectedFragmentPosition;
    }
}

片段看起来像这样:

  public class SectionFragment extends ListFragment implements 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 arg0)
    {
        // TODO Auto-generated method stub
        Log.w("onpage", "onpage executed");
        currentSelectedFragmentPosition = arg0;
    }

    public int getCurrentSelectedFragmentPosition()
    {
        return currentSelectedFragmentPosition;
    }
}

但两者都没有用,对我来说在片段中使用它是最有用的,但如果不可能,那么活动或者statepager也会起作用

1 个答案:

答案 0 :(得分:0)

AppSectionsPagerAdapter构造函数中:添加此

mViewPager.setOnPageChangeListener(this);

(这假设ViewPager是一个名为mViewPager的实例变量)

或者,作为MainActivity.onCreate()中的替代方案:

mViewPager.setOnPageChangeListener(mAppSectionPageAdapter);

(假设AppSectionPageAdapter位于名为mAppSectionPageAdapter的变量中)