美文网首页
FragmentStatePagerAdaper中获取到对应的F

FragmentStatePagerAdaper中获取到对应的F

作者: 晓风残月酒醒 | 来源:发表于2019-05-21 15:10 被阅读0次

FragmentStatePagerAdaper虽然对于节省内存这方面存在一定的优势,但是如果想根据位置获取到对应的Fragment的话,还是存在一定的麻烦,添加一个页面位置和Fragment的对应Map作为成员变量就能简单的解决这个问题

import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.view.ViewGroup;

import java.util.Map;

public abstract class BasePagerAdapter extends FragmentStatePagerAdapter {
    private Map<Integer, Fragment> mPageReferenceMap;      // 位置和页面的对应表

    public BasePagerAdapter(FragmentManager fm) {
        super(fm);
        mPageReferenceMap = new HashMap<Integer, Fragment>();
    }

    @NonNull
    @Override
    public Fragment instantiateItem(@NonNull ViewGroup container, int position) {
        Fragment fragment = (Fragment) super.instantiateItem(container, position);
        // 添加到表中,不能在getItem方法里面添加,有的时候FragmentStatePagerAdapter会恢复一些Fragment,那些Fragment的恢复不会调用getItem方法
        mPageReferenceMap.put(position, fragment);
        return fragment;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        // 从表中删除
        mPageReferenceMap.remove(position);
        super.destroyItem(container, position, object);
    }

    // 根据位置获取到对应的页面,使用的时候也需要判空和判定 !fragment.isDetached() && !fragment.isRemoving(),否则会引发一些隐藏的问题
    public Fragment getFragment(int position) {
        return mPageReferenceMap.get(position);
    }

    /**
     * 由于 fragment.setArguments(); 方法传递的参数会被 FragmentStatePagerAdapter 所缓存
     * ,为了节省内存,重写这个方法返回空可以阻止FragmentStatePagerAdapter的缓存操作
     * @return
     */
    @Override
    public Parcelable saveState() {
        return null;
    }
}

相关文章

网友评论

      本文标题:FragmentStatePagerAdaper中获取到对应的F

      本文链接:https://www.haomeiwen.com/subject/bokjzqtx.html