如何从堆栈中弹出片段

我有一个活动 A,它调用片段 Bf,它调用片段 Cf。我希望在调用 Cf 时,Bf 放在回栈中,这样用户就可以导航回它。但是,如果在 Cf 中按下了某个特定的按钮,我希望将 Bf 从堆栈中删除。这可能吗?

我看到有一个 popBackStack ()函数。然而,我有点困惑,这将如何工作。使用这个函数是否安全?来自不同应用程序的活动是否有可能插入到 Bf 之后的回栈中?

另外,是否有任何方法可以改变后台堆栈上片段的另存 InstanceState?

我只是不知道如何使用模拟器在回栈上进行健壮的测试。

99266 次浏览

You can pop the fragment by name. While adding fragments to the back stack, just give them a name.

fragmentTransaction.addToBackStack("fragB");
fragmentTransaction.addToBackStack("fragC");

Then in Fragment_C, pop the back stack using the name ie.. fragB and include POP_BACK_STACK_INCLUSIVE

someButtonInC.setOnClickListener(new View.OnClickListener() {


@Override
public void onClick(View v) {


FragmentManager fm = getActivity()
.getSupportFragmentManager();
fm.popBackStack ("fragB", FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
});

Three ways to pop Fragment off BackStack

Simply add any of these lines:

1)

getActivity().getSupportFragmentManager().popBackStack();

2)

getActivity().getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);

3)

getActivity().getSupportFragmentManager().popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);

They're all easy ways to pop fragment off Backstack

first replacing fragment container_view that time we add name as like "Later Transaction"

   getSupportFragmentManager().beginTransaction().replace(R.id.container_view,
profileFragment, "Profile").addToBackStack("Later Transaction").commit();

then on back press button pop the back stack using the Later Transaction name

     int count = getSupportFragmentManager().getBackStackEntryCount();
if(count > 1) {
getSupportFragmentManager().popBackStack("Later Transaction",
FragmentManager.POP_BACK_STACK_INCLUSIVE);
} else {
DialogUtils.show(HomeActivity.this,
getString(R.string.exit_app_message), getString(R.string.alert),
"Yes","No", new DialogUtils.ActionListner() {
@Override
public void onPositiveAction() {
finish();
}
@Override
public void onNegativeAction() {
}
});
}

Here's example to pop last fragment using BackStackEntry

val manager = supportFragmentManager
try {
// get last entry (you can get another if needed)
val entry = manager.getBackStackEntryAt(manager.backStackEntryCount - 1)
// you can pop it by name
manager.popBackStack(entry.name, FragmentManager.POP_BACK_STACK_INCLUSIVE)
// or pop by id
manager.popBackStack(entry.id, FragmentManager.POP_BACK_STACK_INCLUSIVE)
} catch (ex: Exception) {
ex.printStackTrace()
}

You can try this way

val fm= parentFragmentManager
fm.popBackStack("group", FragmentManager.POP_BACK_STACK_INCLUSIVE)