Wednesday, 21 September 2022

onBackPressedDispatcher.onBackPressed() vs backPressedCallback.handleOnBackPressed()

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?



from onBackPressedDispatcher.onBackPressed() vs backPressedCallback.handleOnBackPressed()

No comments:

Post a Comment