Search code examples
androidandroid-fragmentsfragmentmanagerfragment-lifecycle

What event of Fragment will be called when I click device back?


I am adding a fragment B on top of another fragment A as follows:

fragmentManager.beginTransaction().add(R.id.frame_container, fragment).addToBackStack("post_details").commit();

The issue is, when I click on device back on B, I need an anchor in A. Which lifecycle method will be called in this case?


Solution

  • It depends on the type of transaction you use and whether you added the fragment to the back stack. Let's go through the scenarios assuming you added B to the backstack and your Activity doesn't go through any lifecycle events:

    • Add A -> Add B + addToBackstack -> popBackStack

      In this case, A will go through no lifecycle events.

    • Add A -> Replace with B + addToBackStack -> popBackStack

      In this case, A will go through onCreateView->onActivityCreated and so on.

    Now on your other question, how can A know whether B is being removed? There are many ways, but an easy one is for B to check Fragment.isRemoving in its own onPause. Then, B can notify the hosting Activity or even Fragment A that it's being removed.