How does one go about hijacking the back button th...
# compose
d
How does one go about hijacking the back button the same way a DropdownMenu or AlertDialog does?
BackHandler
?
1
i
BackHandler
is precisely for handling the back button in a composable, yes
d
@Ian Lake Thanks! If the host activity does not call
super.onBackPressed()
it won’t work correct?
NVM I answered my own question. The answer is yes.
@Colton Idle ☝️
i
Correct, none of the default behavior, such as dispatching to the activity's
OnBackPressedDispatcher
will occur if you don't call
super.onBackPressed()
tl/dr: it is 2021, you shouldn't be overriding
onBackPressed()
at all - you should only be using the
OnBackPressedDispatcher
APIs and those built on top of it
👍 2
There's also docs on using those APIs in the non-Compose world: https://developer.android.com/guide/navigation/navigation-custom-back
d
Oh fantastic!
I am building a launcher and custom alert dialogs so this is super handy!
👍 1
i
Yeah, just keep in mind how key events dispatch works on Android - keys are sent to the topmost window. This is how a
PopupWindow
or
android.app.Dialog
will steal the back button before your activity (and its
OnBackPressedDispatcher
) receives the key event
That generally means that you should avoid having a back stack in any temporary windows
d
Noted!