解决 ViewPage setAdapter()不更新数据的bug

public class HomeAdapter extends FragmentPagerAdapter {

    List<IndexDataEntity.DataBean.MorenBean> morenBeanList;
    private FragmentManager fm;

    public HomeAdapter(FragmentManager fm, List<IndexDataEntity.DataBean.MorenBean> morenBeanList) {
        super(fm);
        this.fm = fm;
        this.morenBeanList = morenBeanList;
    }

    @Override
    public HomePageFragment getItem(int position) {
        return HomePageFragment.newInstance(Integer.parseInt(morenBeanList.get(position).getId()), Integer.valueOf(morenBeanList.get(position).getParametertype()));
    }

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

    @Override
    public CharSequence getPageTitle(int position) {
        return morenBeanList.get(position).getParametername();
    }


    /**
     * 重写FragmentPagerAdapter里边的方法,如果fragment存在的话会调用缓存里边的fragment
     * 从而导致数据不更新问题
     *
     * @param container
     * @param position
     * @return
     */
    public Object instantiateItem(ViewGroup container, int position) {
        //拿到缓存的fragment,如果没有缓存的,就新建一个,新建发生在fragment的第一次初始化时
        HomePageFragment f = (HomePageFragment) super.instantiateItem(container, position);
        String fragmentTag = f.getTag();
        if (f != getItem(position)) {
            //如果是新建的fragment,f 就和getItem(position)是同一个fragment,否则进入下面
            FragmentTransaction ft = fm.beginTransaction();
            //移除旧的fragment
            ft.remove(f);
            //换成新的fragment
            f = getItem(position);
            //添加新fragment时必须用前面获得的tag
            ft.add(container.getId(), f, fragmentTag);
            ft.attach(f);
            ft.commitAllowingStateLoss();
        }
        return f;
    }


}

 

展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读