OnBackPressedDispatcher

public final class OnBackPressedDispatcher


Dispatcher that can be used to register OnBackPressedCallback instances for handling the onBackPressed callback via composition.

public class FormEntryFragment extends Fragment {
    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        OnBackPressedCallback callback = new OnBackPressedCallback(
            true // default to enabled
        ) {
            @Override
            public void handleOnBackPressed() {
                showAreYouSureDialog();
            }
        };
        requireActivity().getOnBackPressedDispatcher().addCallback(
            this, // LifecycleOwner
            callback);
    }
}

Summary

Public constructors

Create a new OnBackPressedDispatcher that dispatches System back button pressed events to one or more OnBackPressedCallback instances.

OnBackPressedDispatcher(@Nullable Runnable fallbackOnBackPressed)

Create a new OnBackPressedDispatcher that dispatches System back button pressed events to one or more OnBackPressedCallback instances.

Public methods

@MainThread void
addCallback(@NonNull OnBackPressedCallback onBackPressedCallback)

Add a new OnBackPressedCallback.

@MainThread void
addCallback(
    @NonNull LifecycleOwner owner,
    @NonNull OnBackPressedCallback onBackPressedCallback
)

Receive callbacks to a new OnBackPressedCallback when the given LifecycleOwner is at least started.

@MainThread boolean

Checks if there is at least one enabled callback registered with this dispatcher.

@MainThread void

Trigger a call to the currently added callbacks in reverse order in which they were added.

Extension functions

final @NonNull OnBackPressedCallback
OnBackPressedDispatcherKt.addCallback(
    OnBackPressedDispatcher receiver,
    LifecycleOwner owner,
    boolean enabled,
    @