I just wanted to add :--
Popping out from backstack using following
fragmentManager.popBackStack()
is just about removing the fragments from the transaction, no way it is going to remove the fragment from the screen.
So ideally, it may not be visible to you but there may be two or three fragments stacked over each other, and on back key press the UI may look cluttered,stacked.
Just taking a simple example:-
Suppose you have a fragmentA which loads Fragmnet B using fragmentmanager.replace() and then we do addToBackStack, to save this transaction.
So the flow is :--
STEP 1 -> FragmentA->FragmentB (we moved to FragmentB, but Fragment A is in background, not visible).
Now You do some work in fragmentB and press the Save button—which after saving should go back to fragmentA.
STEP 2-> On save of FragmentB, we go back to FragmentA.
STEP 3 ->So common mistake would be... in Fragment B,we will do fragment Manager.replace() fragmentB with fragmentA.
But what actually is happenening, we are loading Fragment A again, replacing FragmentB . So now there are two FragmentA (one from STEP-1, and one from this STEP-3).
Two instances of FragmentsA are stacked over each other, which may not be visible , but it is there.
So even if we do clear the backstack by above methods, the transaction is cleared but not the actual fragments.
So ideally in such a particular case, on press of save button you simply need to go back to fragmentA by simply doing fm.popBackStack() or fm.popBackImmediate().
So correct Step3-> fm.popBackStack() go back to fragmentA, which is already in memory.