Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to back to the root fragment or top of hierarchy using Navigation Controller Component in Android?

let say I have 4 tabs in bottom navigation view. and if the user choose one of those tabs, then the user will navigate from one fragment to other fragments.

let say user choose the first tab (home), and then navigate from:

fragmentA (home) -> fragmentB -> fragmentC -> fragmentD -> fragmentE

I want to back from fragmentE to fragmentA programmatically using navigation controller component in Android. how to do that ?

I have tried using this code, but it just went back to fragmentD (form fragmentE)

btn.setOnClickListener{
 Navigation.findNavController(view).navigateUp()
}
like image 411
Agung Laksana Avatar asked Oct 17 '25 09:10

Agung Laksana


1 Answers

NavController's popBackStack(int, boolean) pops back to a specific destination id:

Attempts to pop the controller's back stack back to a specific destination.

Therefore you can use

Navigation.findNavController(view).popBackStack(R.id.fragmentA, false)

To pop back to fragmentA without popping fragmentA itself (which is why the inclusive flag is false).

like image 65
ianhanniballake Avatar answered Oct 18 '25 23:10

ianhanniballake



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!