Android predictive back gesture - how to make it to work?

Viewed 63

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()

}
1 Answers

you won't be able to see predictive back unless you go to developer settings of emulator/device and enable predictive back setting apart from code changes and manifest condition to enable it. and currently its only enabled for going back from home screen showing launcher preview

you can follow code lab example here https://codelabs.developers.google.com/handling-gesture-back-navigation#0

Related