Since the old Activity.onBackPressed()
becomes deprecated starting Android 33, what is the better way to call it programmatically?
Example:
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
// Handle default back arrow click
android.R.id.home -> {
onBackPressed()
}
...
We could create and add OnBackPressedCallback
to the onBackPressedDispatcher
like this.
onBackPressedDispatcher.addCallback(
this, // Lifecycle owner
backPressedCallback
)
private val backPressedCallback = object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
if (viewPager.currentItem != 0)
viewPager.setCurrentItem(0, true)
else
finish()
}
}
Then replace the old onBackPressed
with
// Handle default back arrow click
android.R.id.home -> {
backPressedCallback.handleOnBackPressed()
}
But I saw this public method in onBackPressedDispatcher
and wondering if I could use it instead.
onBackPressedDispatcher.onBackPressed()
Does this method iterates on each OnBackPressedCallback
that has been added in the onBackPressedDispatcher
?
OnBackInvokedCallback
to an Activity'sonBackInvokedDispatcher
replaces usages of custom back invocations usually put inonBackPressed()
. Fragments on the other hand useonBackPressedDispatcher
/OnBackPressedCallback
addCallback
. This can cause some issue like when your activity goes to onPause and onStop because another activity was open above it or the app was to minimize, the added callback will be remove internally in this case. Other possible reason is you set false during initialization ofOnBackPressedCallback(false)
or set the callback.isEnabled
to false which also prevent it to work.