markdown 如何在ViewPager中检索当前片段

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown 如何在ViewPager中检索当前片段相关的知识,希望对你有一定的参考价值。

# How To Retrieve The Current `Fragment` in `ViewPager`

[SOURCE](https://stackoverflow.com/a/15261142/1602807)

The key point is to override `instantiateItem()` and `destroyItem()` of your `Fragment(State)PagerAdapter`:

```java
public class MyPagerAdapter extends FragmentStatePagerAdapter {
    SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();

    public MyPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public int getCount() {
        return ...;
    }

    @Override
    public Fragment getItem(int position) {
        return MyFragment.newInstance(...); 
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        Fragment fragment = (Fragment) super.instantiateItem(container, position);
        registeredFragments.put(position, fragment);
        return fragment;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        registeredFragments.remove(position);
        super.destroyItem(container, position, object);
    }

    public Fragment getRegisteredFragment(int position) {
        return registeredFragments.get(position);
    }
}
```

This seems to work for me when dealing with Fragments that are available. Fragments that have not yet been instantiated, will return null when calling `getRegisteredFragment()`. But I've been using this mostly to get the current `Fragment` out of the `ViewPager`: `adapater.getRegisteredFragment(viewPager.getCurrentItem())` and this won't return `null`.

以上是关于markdown 如何在ViewPager中检索当前片段的主要内容,如果未能解决你的问题,请参考以下文章

如何在ViewPager中重用Fragment实例?

当 ViewPager 中的片段出现和消失时如何执行一些代码

如何在 Android 中向 ViewPager 添加进度条

无法将数据从RecyclerView适配器传递到Viewpager适配器

如何将 Android ViewPager2 的高度包装到当前项目的高度?

如何将值从其他活动传递给 viewpager 片段?