I want to clear selection on back button pressed on selection tracker when there are selected items and use default back button functionallity if there are no selected items.
I use Navigation Components for working with fragments.
Code in my fragment which implements OnBackPressedListener interface:
override fun onBackPressed() {
if (tracker?.hasSelection() == true) tracker?.clearSelection()
else findNavController().popBackStack()
}
Clear selection condition is working, but else block does not.
Code from my BaseActivity which determines how to use back button.
override fun onBackPressed() {
val currentFragment = navHost.childFragmentManager.fragments[0]
if (currentFragment is OnBackPressedListener) {
currentFragment.onBackPressed()
} else {
super.onBackPressed()
}
}
So, question is how to exit fragment (or pop backstack) when there are no selected items in selection tracker? It is working when I call
requireActivity().finish()
, but I do not know if this is correct solution.
For this case, you could try registering OnBackPressedCallback on your Fragments via addOnBackPressedCallback. For more detail follow the below-given link:
https://developer.android.com/guide/navigation/navigation-custom-back
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.