Skip to content
Go back

Predictive back gestures migration

Published:

Table of Contents

Open Table of Contents

The Concept

What is it?

What it implies?

Hows it implemented?

What it changes?

The mental model change: callbacks are to be used temporarily!

Previously the only option was to override onBackPressed() and thus listen for the duration of the activity. Imagine users EditText is in a wrong state and thus we want to block the back press. You likely had some code in onBackPressed that checked with EditText if back can proceed or not. With callbacks this approach is an antipattern. Now you should reactively enable a callback as soon as EditText is in a wrong state, and disable it as soon as it exits that state. Only by adapting to this new mindset you allow the framework to do the predictive animations. Blindly copying logic from onBackPressed() to callbacks is a mistake.

Tech notes:

Enabling it:

Listener APIs:

After enabling predictive back gestures:

Programmatically invoking onBackPressed:

Logging back presses

As mentioned above, adding a callback means you handle it now - you lose animations, and only single callback is invoked. Thus transparently doing something trivial like logging/analytics on back press is now impossible.

Workaround can be focusing on navigation changes instead. Adding OnBackStackChangedListener to FragmentManager, or observing the backstack size in compose navigation.

The platform callback on API 36 got PRIORITY_SYSTEM_NAVIGATION_OBSERVER for a similar purpose. This means you can add a low priority listener that does not interfere with predictive animations. But all the caveats still apply:

So it can be unpredictable as it depends very much on app state.



Next Post
Passing arguments to Android ViewModel