androidkotlinandroid-fragmentsfragment-backstack

How to handle back-stack in Fragment?


case 1: I have 3 fragments A,B,C. When I am moving from A->B->C and then by pressing a save button on C fragment , I come back to fragment B and now when I press the back button at this point (in fragment B), it takes me to fragment C (C fragment is stored in the backstack) but I need to take the user to fragment A instead of C.

---> I am using this below code when user presses on back button of fragment B.

navController!!.popBackStack()

case 2: When I am moving A->B and now if I press back button it takes me back to fragment A. (This is working fine) . But in above case (case 1), it takes the user to fragment C instead of A.

How should I handle this backstack case?


Solution

  • call same code

    navController!!.popBackStack()
    

    after saving button click and before redirection to B fragment

    so in C Fragment code will be

    //save button clicked 
    // you logic and code 
    navController!!.popBackStack()
    //navigate back to B fragment 
    
    navController!!.navigate(B fragment ID)