美文网首页
笔记68 | 切换fragmengt的replace和add方法

笔记68 | 切换fragmengt的replace和add方法

作者: 项勇 | 来源:发表于2018-04-14 15:12 被阅读9次

    replace

       private  void  LoandFragment(Fragment fragment){
            FragmentManager fm = getSupportFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();
            ft.replace(R.id.fragment, fragment);
            ft.commitAllowingStateLoss();
        }
    
    运行情况

    add

     private Fragment currentFragment = new Fragment();
        //Fragment优化
        private FragmentTransaction transaction(Fragment targetFragment) {
    
            FragmentTransaction transaction = getSupportFragmentManager()
                    .beginTransaction();
            if (!targetFragment.isAdded()) {
                //第一次使用switchFragment()时currentFragment为null,所以要判断一下
                if (currentFragment != null) {
                    transaction.hide(currentFragment);
                }
                transaction.add(R.id.fragment, targetFragment, targetFragment.getClass().getName());
    
            } else {
                transaction
                        .hide(currentFragment)
                        .show(targetFragment);
            }
            currentFragment = targetFragment;
            return transaction;
        }
    
    运行情况

    性能没什么区别~~~

    相关文章

      网友评论

          本文标题:笔记68 | 切换fragmengt的replace和add方法

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