Fragment系列文章(三) - 解决思路

1. 解决思路

如果容器中没有就去添加新的Fragment,否则就直接显示,显示之前需要把所有已经添加的不显示(隐藏)

2. FragmentManagerHelper 工具类如下:
/**
 * Email [email protected]
 * Created by Novate on 2018/07/29 10:29:32.
 * Version 1.0
 * Description:
 */
public class FragmentManagerHelper {
    // 管理类FragmentManager
    private FragmentManager mFragmentManager;
    // 容器布局id containerViewId
    private int mContainerViewId;

    /**
     * 构造方法
     */
    public FragmentManagerHelper(@Nullable FragmentManager fragmentManager, @IdRes int containerViewId) {
        this.mFragmentManager = fragmentManager;
        this.mContainerViewId = containerViewId;
    }

    /**
     * 添加Fragment
     */
    public void add(Fragment fragment){
        // 开启事物
        FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
        // 第一个参数是Fragment的容器id,需要添加的Fragment
        fragmentTransaction.add(mContainerViewId, fragment);
        // 一定要commit
        fragmentTransaction.commit();
    }

    /**
     * 切换显示Fragment
     */
    public void switchFragment(Fragment fragment){
        // 开启事物
        FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();

        // 1.先隐藏当前所有的Fragment
        List childFragments = mFragmentManager.getFragments();
        for (Fragment childFragment : childFragments) {
            fragmentTransaction.hide(childFragment);
        }

        // 2.如果容器里面没有我们就添加,否则显示
        if(!childFragments.contains(fragment)){
            fragmentTransaction.add(mContainerViewId,fragment);
        }else{
            fragmentTransaction.show(fragment);
        }

        // 一定要commit
        fragmentTransaction.commit();
    }
}

你可能感兴趣的:(Fragment系列文章(三) - 解决思路)