fragment切换保存代码

最近公司新招了安卓,自己负责带着他,总共也就几个程序,,,苦逼的不说了,新来的哥们不给力。fragement 切换保存状态,百度都没实现,自己以前写过,也发出来参考下:
以前使用replace的,每次都会重新执行oncreateView,

     Fragment fragment = Fragment.instantiate(this,
     fragmentClass.getName(),
     arguments);
     FragmentManager fm = getSupportFragmentManager();
     fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);

     FragmentTransaction transaction = fm.beginTransaction();

     if (isFromRightInAni == true)
     transaction.setCustomAnimations(R.anim.right_in, R.anim.left_out,
     R.anim.left_in, R.anim.right_out);
     else
     transaction.setCustomAnimations(R.anim.left_in, R.anim.right_out,
     R.anim.left_in, R.anim.right_out);
     transaction.show(fragment);
     transaction.replace(R.id.content_frame, fragment);
     transaction.commit();

后面改用hide和show来实现:

Fragment newFragment = fragments[currentIndex];
    FragmentTransaction transaction = getSupportFragmentManager()
            .beginTransaction();

    if (getSupportFragmentManager().getFragments() == null
            || !getSupportFragmentManager().getFragments().contains(
                    fragments[currentIndex])) {
        transaction.add(R.id.content_frame, newFragment);
    }

    transaction.addToBackStack(null);
    if (tabIndex > -1)
        transaction.hide(fragments[tabIndex]);
    transaction.show(newFragment);

    transaction.commit();
    tabIndex = currentIndex;

你可能感兴趣的:(fragment切换保存代码)