欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ViewPager动态增加或删除fragment问题

程序员文章站 2022-04-20 08:29:14
...

项目开发过程中,对ViewPager里的frament进项动态删除和替换,然后调用pagerAdapter.notifyDataSetChanged(),发现wtf根本无效果。最后想百度下解决办法,基本就是一点点原理搬来搬去,对这些复制粘贴真的无感。(原理百度上都有)这里只写实现逻辑。

业务场景:根据操作类别,显示不同的业务fragment。(企业app软件常见)

pagerAdapter类:(这里继承的是FragmentPagerAdapter )

public class ForceFlushPagerAdapter extends FragmentPagerAdapter {

    private int mChildCount = 0;
    private FragmentManager fm;
    private List<String> tittleList;
    private List<Fragment> mFragments;

    public ForceFlushPagerAdapter(FragmentManager fm, List<String> tittleList, List<Fragment> mFragments) {
        super(fm);
        this.fm = fm;
        this.tittleList = tittleList;
        this.mFragments = mFragments;
    }
    @Override
    public Fragment getItem(int position) {
        return mFragments.get(position);
    }

    @Override
    public void notifyDataSetChanged() {
        mChildCount = getCount();
        super.notifyDataSetChanged();
    }

    @Override
    public int getItemPosition(Object object) {
        if ( mChildCount > 0) {  //这一部分必须要
            // 这里利用判断执行若干次不缓存,刷新
            mChildCount --;
            // 返回这个是强制ViewPager不缓存,每次滑动都刷新视图
            return POSITION_NONE;
        }
        return super.getItemPosition(object);
    }
    @Override
    public int getCount() {
        return mFragments.size();
    }

    @Override
    public Fragment instantiateItem(ViewGroup container, int position) {
        Fragment fragment = (Fragment) super.instantiateItem(container, position);
        fm.beginTransaction().show(fragment).commit();
        return  fragment;
    }

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

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        if (position >= getCount()) return;
        Fragment fragment = mFragments.get(position);
        fm.beginTransaction().hide(fragment).commit();
    }
}

替换ViewPager中的Fragment,我有两个完全不同的fragment,定名TypeFragment1、TypeFragment2。在操作前你需要知道你的fragment被谁管理(FragmentManager是一个final对象,在FragmentActivity初始化),ViewPager只是一个容器。

替换Fragment的代码:

private void updateFragments() {
    //移除之前的Fragment
    FragmentManager fm = getSupportFragmentManager();
    if (!mFragments.isEmpty()) {
        FragmentTransaction ft = fm.beginTransaction();
        for (Fragment f : mFragments) {
            ft.remove(f);
        }
        ft.commit();
        ft = null;
        fm.executePendingTransactions();
    }
    mFragments.clear();

    for (int i = 0; i < 3; i ++) {
        if (switchTag == 0) {   //switchTag 不同类别
           mFragments.add(TypeFragment1.newInstance());
        } else mFragments.add(TypeFragment2.newInstance());
    }
    pagerAdapter.notifyDataSetChanged();
}
相关标签: android Ui