FragmentManager 清理 .addToBackStack

FragmentManager clean up for .addToBackStack

有什么方法可以使它更干净一点吗?我知道什么时候 query = "" 我在主菜单,因此返回应该关闭应用程序。

        if (query == "") {
            fragmentManager.beginTransaction()
                    .replace(containerId, fragment, tag)
                    .commitAllowingStateLoss();
        } else {
            fragmentManager.beginTransaction()
                    .replace(containerId, fragment, tag)
                    .addToBackStack(null)
                    .commitAllowingStateLoss();
        }

是的,你可以 clean-up 你的片段 activity 一个接一个,这是代码...

   public static void clearBackStack() {
        FragmentManager fm = mainActivity.getSupportFragmentManager();
        for (int i = 0; i < fm.getBackStackEntryCount(); ++i) {
             fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
        }
    }

好的,这对我来说更好。虽然我很欣赏上面的回答。

    FragmentTransaction transaction = fragmentManager.beginTransaction();
    transaction.replace(containerId, fragment, tag);
     if (query != "") {
         transaction.addToBackStack(null);
     }
     transaction.commitAllowingStateLoss();