Retrieve a Fragment from a ViewPager

2018-12-31 01:35发布

I'm using a ViewPager together with a FragmentStatePagerAdapter to host three different fragments:

  • [Fragment1]
  • [Fragment2]
  • [Fragment3]

When I want to get Fragment1 from the ViewPager in the FragmentActivity.

What is the problem, and how do I fix it?

23条回答
临风纵饮
2楼-- · 2018-12-31 02:23

Another simple solution:

    public class MyPagerAdapter extends FragmentPagerAdapter {
        private Fragment mCurrentFragment;

        public Fragment getCurrentFragment() {
            return mCurrentFragment;
        }
//...    
        @Override
        public void setPrimaryItem(ViewGroup container, int position, Object object) {
            if (getCurrentFragment() != object) {
                mCurrentFragment = ((Fragment) object);
            }
            super.setPrimaryItem(container, position, object);
        }
    }
查看更多
唯独是你
3楼-- · 2018-12-31 02:24
Fragment yourFragment = yourviewpageradapter.getItem(int index);

index is the place of fragment in adapter like you added fragment1 first so retreive fragment1 pass index as 0 and so on for rest

查看更多
弹指情弦暗扣
4楼-- · 2018-12-31 02:26

For my case, none of the above solutions worked.

However since I am using the Child Fragment Manager in a Fragment, the following was used:

Fragment f = getChildFragmentManager().getFragments().get(viewPager.getCurrentItem());

This will only work if your fragments in the Manager correspond to the viewpager item.

查看更多
笑指拈花
5楼-- · 2018-12-31 02:27

In order to get current Visible fragment from ViewPager. I am using this simple statement and it's working fine.

      public Fragment getFragmentFromViewpager()  
      {
         return ((Fragment) (mAdapter.instantiateItem(mViewPager, mViewPager.getCurrentItem())));
      }
查看更多
梦该遗忘
6楼-- · 2018-12-31 02:27

Hey I have answered this question here. Basically, you need to override

public Object instantiateItem(ViewGroup container, int position)

method of FragmentStatePagerAdapter.

查看更多
流年柔荑漫光年
7楼-- · 2018-12-31 02:29

Best solution is to use the extension we created at CodePath called SmartFragmentStatePagerAdapter. Following that guide, this makes retrieving fragments and the currently selected fragment from a ViewPager significantly easier. It also does a better job of managing the memory of the fragments embedded within the adapter.

查看更多
登录 后发表回答