I'm trying to test 'predictive back gesture' feature, implemented in Android 13.
In order to do that, first I've migrated my app to AndroidX API (so got rid of all the usages of onBackPressed
methods), then enabled this feature in Manifest and tried on Pixel 4a with Android 13 installed - it didn't work.
Did some investigation and then finally made it to work by removing all the onBackPressed callbacks within onBackPressedDispatcher
.
My question is - how to make this feature to work, while having registered onBackPressed callbacks in the app?
Update:
abstract class BaseFragment : Fragment() {
private val onBackPressedCallback = object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
onBackPressed()
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner, onBackPressedCallback)
}
// If there are no more items in backstack, `navController.navigateUp()`
// closes the app, which is desired behavior. It's triggered via callback though,
// so, as I understand, that's the reason predictive back gesture doesn't work.
protected open fun onBackPressed() {
if (!navigateUp()) {
onBackPressedCallback.isEnabled = false
requireActivity().onBackPressedDispatcher.onBackPressed()
}
}
// I can override this method in places, where I need to use custom backPressed logic
protected open fun navigateUp(): Boolean = navController.navigateUp()
}