Predictive back

Modern Android Mid-level Kotlin 2.0+ API 24+ Reviewed By Best Latest Apps

Pick the fix

A form screen uses BackHandler(enabled = true) { showDiscardDialog() } and users can't see the back preview even with no changes. Fix?

Options
Hint 1 of 1

When should the handler be active?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A Set enabled = hasUnsavedChanges

Correct. With nothing to save, the system handles back and shows its preview.

Why not the others?
  • B Override onBackPressed instead. Not called when targeting API 36.
  • C Intercept KEYCODE_BACK. Breaks predictive back.
  • D Remove the dialog entirely. Users could lose work.

30-second answer

Predictive back shows a preview of where Back goes while the user swipes, such as the home screen or the previous screen. To support it, stop overriding onBackPressed() or intercepting KEYCODE_BACK and use OnBackPressedDispatcher callbacks, or BackHandler in Compose. For apps targeting API 36 the system animations are on by default and onBackPressed isn't called.

Practise saying it · 25 s. No recording, just a timer

Explain predictive back.

Say your answer out loud, then check which of these points you covered:

  • Preview while swiping
  • Dispatcher callbacks or BackHandler
  • Enable only when needed
  • Default at API 36

Deep dive

Enable callbacks only when they'll handle back, such as unsaved changes, so the system can show the right preview.

Navigation Compose and Fragments support predictive back animations.

PredictiveBackHandler receives swipe progress for custom animations.

Back-to-home preview needs no code beyond not intercepting back.

Back only when there's something to lose Compile-checked · Kotlin 2.4.21
@Composable
fun EditNote(hasUnsavedChanges: Boolean, onAskDiscard: () -> Unit) {
    BackHandler(enabled = hasUnsavedChanges) { onAskDiscard() }
    Text("Editing")
}

Common mistakes

  • Overriding onBackPressed.
  • A BackHandler that's always enabled, which blocks the home preview.
  • Showing an 'Are you sure?' dialog on every back.

Senior take & follow-ups

Explain why the system needs to know ahead of time, then the APIs.

Follow-up questions

Think of your answer first, then open the hint.

  1. Why must the callback be enabled only when needed?

    Show hint

    The system decides the preview before the gesture finishes.

  2. What replaced onBackPressed?

    Show hint

    OnBackPressedDispatcher callbacks.

Suggest a fix if something here is wrong or out of date.