Skip some fragments onBackPressed

前端 未结 3 1496
[愿得一人]
[愿得一人] 2021-02-05 16:28

I am fairly new with android fragments so please bear with me.

I have a bunch of fragments using a single activity as host.

In my mind, my fragments are grouped

3条回答
  •  时光取名叫无心
    2021-02-05 17:04

    When you display Frag2 use:

    final FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.addToBackStack(FRAG_2);
    fragmentTransaction.replace(containerID, frag2, FRAG2_TAG);
    

    and on back press:

    @Override
    public void onBackPressed() {
       final Frag2 frag2 = (Frag2)getSupportFragmentManager().findFragmentByTag(FRAG2_TAG);
       if (frag2 != null && frag2.isVisible() && getSupportFragmentManager().getBackStackEntryCount() > 0) {
        getSupportFragmentManager().popBackStackImmediate();
        return;
       }
    }
    

    This will prevent from frag2 to be displayed after onBackPressed() called. Avoid using popBackStack() as this will results in frag2 lifecycle trigger (onCreate, onStart, onResume ...)

提交回复
热议问题