动态管理fragment

来源:互联网 发布:淘宝里面怎么投诉卖家 编辑:程序博客网 时间:2024/05/21 13:22
 /**
     * 该方法用于Fragment切换
     * @param containerId 容器ID
     * @param fragmentClass 要切换的Fragment 目标Fragment
     * @param bundle 跳转Fragment是要传递的参数
     * @param isReplace 是否替换当前Fragment true:replace替换 false :hind 隐藏
     * @param isBack 该Fragment是否要添加至回退栈
     */
    public void changFragment(int containerId, Class<? extends BaseFragment> fragmentClass, Bundle bundle, boolean isReplace, boolean isBack){
        //获取Fragment管理器
        FragmentManager manager = getSupportFragmentManager();
        //获取Fragment类名 下面会用到类名做Tag
        String fragmentName = fragmentClass.getSimpleName();
        //开启事务
        FragmentTransaction transaction = manager.beginTransaction();
        //通过Tag来查找Fragment  如果查找到返回的就是该Fragment对象 否则是null 代表该Fragment没有被创建过
        BaseFragment currentFragment = (BaseFragment) manager.findFragmentByTag(fragmentName);
        //如果Fragment为null 就通过Java动态代理创建对应的Fragment对象
        if(currentFragment == null){
            try {
                //通过Java动态代理创建Fragment
                currentFragment = fragmentClass.newInstance();
                transaction.add(containerId,currentFragment,fragmentName);
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        //isReplace 为true代表替换
        if(isReplace) {
            transaction.replace(containerId, currentFragment, fragmentName);
        } else {
            //隐藏上一个Fragment
            if(lastFragment != null)
                transaction.hide(lastFragment);
            //显示当前的Fragment
            transaction.show(currentFragment);
        }
        //bundle 不等于null代表要传递参数
        if(bundle != null) {
            currentFragment.setParams(bundle);


        }
        //isBack为true是添加至回退栈
        if (isBack){
            transaction.addToBackStack(fragmentName);
        }


        transaction.commit();
        lastFragment = currentFragment;
    }
阅读全文
0 0