Android FragmentStatePagerAdapter, how to tag a fragment to find it later

前端 未结 9 1254
独厮守ぢ
独厮守ぢ 2020-12-24 14:09

When using the FragmentStatePageAdapter I get the fragments like this:

    @Override
    public Fragment getItem(int position) {
        return          


        
9条回答
  •  滥情空心
    2020-12-24 14:50

    * EDIT *

    As @ElliotM pointed out, there is a better solution. No need to change anything in your adapter, just get the fragment with:

    Fragment myFragment = (Fragment) adapter.instantiateItem(viewPager, viewPager.getCurrentItem());
    

    * OLD SOLUTION *

    Best option is the second solution here: http://tamsler.blogspot.nl/2011/11/android-viewpager-and-fragments-part-ii.html

    In short: you keep track of all the "active" fragment pages. In this case, you keep track of the fragment pages in the FragmentStatePagerAdapter, which is used by the ViewPager..

    public Fragment getItem(int index) {
        Fragment myFragment = MyFragment.newInstance();
        mPageReferenceMap.put(index, myFragment);
        return myFragment;
    }
    

    To avoid keeping a reference to "inactive" fragment pages, we need to implement the FragmentStatePagerAdapter's destroyItem(...) method:

    public void destroyItem(View container, int position, Object object) {
        super.destroyItem(container, position, object);
        mPageReferenceMap.remove(position);
    }
    

    ... and when you need to access the currently visible page, you then call:

    int index = mViewPager.getCurrentItem();
    MyAdapter adapter = ((MyAdapter)mViewPager.getAdapter());
    MyFragment fragment = adapter.getFragment(index);
    

    ... where the MyAdapter's getFragment(int) method looks like this:

    public MyFragment getFragment(int key) {
        return mPageReferenceMap.get(key);
    }
    

    --- EDIT:

    Also add this in your adapter, for after an orientation change:

    /**
     * After an orientation change, the fragments are saved in the adapter, and
     * I don't want to double save them: I will retrieve them and put them in my
     * list again here.
     */
    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        MyFragment fragment = (MyFragment) super.instantiateItem(container,
                position);
        mPageReferenceMap.put(position, fragment);
        return fragment;
    }
    

提交回复
热议问题