Home > Software design >  How to show a dialog to confirm that the user wishes to exit an App?
How to show a dialog to confirm that the user wishes to exit an App?

Time:10-13

The answer here using onBackPressed() is deprecated.

How to show a dialog to confirm that the user wishes to exit an Android Activity?

What's the new approach? Also, My activity contains fragments and I am using Navigation Component, onBackPressed() also triggered when I am inside fragment, need to avoid it.

CodePudding user response:

I think you are looking for something like that https://developer.android.com/reference/androidx/activity/OnBackPressedDispatcher

CodePudding user response:

If you are using a navigation graph then you should try this code.

onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true) {
        override fun handleOnBackPressed() {
            try {
                    val count = supportFragmentManager.findFragmentById(R.id.fragmentContainerView)
                        ?.childFragmentManager?.backStackEntryCount ?: 0
                    if (count == 0) showExitSnackBar()
                }catch (e:Exception){
                    e.printStackTrace()
                }
        }
    })
  • Related