使用 backstack 和静态结构模式在片段之间导航

首先,我们需要在开头添加我们的第一个 Fragment,我们应该在我们的 Activity 的 onCreate() 方法中做到:

if (null == savedInstanceState) {
    getSupportFragmentManager().beginTransaction()
      .addToBackStack("fragmentA")
      .replace(R.id.container, FragmentA.newInstance(), "fragmentA")
      .commit();
}

接下来,我们需要管理我们的 backstack。最简单的方法是在我们的活动中添加一个用于所有 FragmentTransactions 的函数。

public void replaceFragment(Fragment fragment, String tag) {
    //Get current fragment placed in container
    Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.container);

    //Prevent adding same fragment on top
    if (currentFragment.getClass() == fragment.getClass()) {
        return;
    }

    //If fragment is already on stack, we can pop back stack to prevent stack infinite growth
    if (getSupportFragmentManager().findFragmentByTag(tag) != null) {
        getSupportFragmentManager().popBackStack(tag, FragmentManager.POP_BACK_STACK_INCLUSIVE);
    }

    //Otherwise, just replace fragment
    getSupportFragmentManager()
            .beginTransaction()
            .addToBackStack(tag)
            .replace(R.id.container, fragment, tag)
            .commit();
}

最后,当从 Backstack 中可用的最后一个 Fragment 返回时,我们应该覆盖 onBackPressed() 以退出应用程序。

@Override
public void onBackPressed() {
    int fragmentsInStack = getSupportFragmentManager().getBackStackEntryCount();
    if (fragmentsInStack > 1) { // If we have more than one fragment, pop back stack
        getSupportFragmentManager().popBackStack();
    } else if (fragmentsInStack == 1) { // Finish activity, if only one fragment left, to prevent leaving empty screen
        finish();
    } else {
        super.onBackPressed();
    }
}

活动执行:

replaceFragment(FragmentB.newInstance(), "fragmentB");

执行外部活动(假设 MainActivity 是我们的活动):

((MainActivity) getActivity()).replaceFragment(FragmentB.newInstance(), "fragmentB");