Closed SyedAsimAliSE closed 5 years ago
Here is how i solved it after wasting an hour to just figure out how to access the selected graph stack in parent activity:
leaving this here to save others time :)
1 Create an Interface
interface NavBackListener {
fun onNavigateBack(from: String?)
}
2 Implement it in MainActivity
override fun onNavigateBack(from: String?) {
//update the bottom nav bar manually & navigate back to home**
bottomNavBar.selectedItemId = R.id.main_nav_home
navController.navigate(R.id.main_nav_home)
}
3 Implement OnBackPressedCallback in the fragments
override fun onActivityCreated(savedInstanceState: Bundle?) {
activity?.addOnBackPressedCallback(viewLifecycleOwner, this)
super.onActivityCreated(savedInstanceState)
}
override fun handleOnBackPressed(): Boolean {
navBackListener?.onNavigateBack(getString(R.string.tab_cats_lbl))
return true
}
override fun onDestroyView() {
super.onDestroyView()
activity?.removeOnBackPressedCallback(this)
}
4 Attach NavBackListener in the fragments
override fun onAttach(context: Context) {
super.onAttach(context)
navBackListener = getListenerOrThrowException(NavBackListener::class.java)
}
override fun onDetach() {
super.onDetach()
navBackListener = null
}
I created sample for back stack. See this commit. https://github.com/STAR-ZERO/navigation-keep-fragment-sample/commit/cc9c0e36de1568a7e4ddd5dc0d72405bb1c0eb6a
Hi, thanks for this most wanted solution , but when you press back on any tab it will exit the app. !
thanks