Search code examples
androidandroidx

Detect if onBackPressed will destroy an Activity?


I'm trying to implement a dialog that confirms the user wants to destroy an activity. Looking at a few other questions, it seems I can override the onBackPressed() functionality to add this dialog. However, my app has navigation between fragments in the same activity so it is possible that the Back button is navigating between fragments and not actually going to destroy the activity. Is my approach going in the right direction or is it fundamentally flawed? If it is idiomatic, the next question is how to determine if the activity will be destroyed or not?

    class GameActivity : AppCompatActivity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_game)
            val navView: BottomNavigationView = findViewById(R.id.game_nav_view)

            val navHostFragment = supportFragmentManager.findFragmentById(R.id.game_nav_host_fragment) as NavHostFragment
            val navController = navHostFragment.navController
            val appBarConfiguration = AppBarConfiguration(setOf(
                    R.id.navigation_fragment_a, R.id.navigation_fragment_b))
            setupActionBarWithNavController(navController, appBarConfiguration)
            navView.setupWithNavController(navController)
        }

        override fun onBackPressed() {
            val builder = AlertDialog.Builder(this)
                    .setTitle(R.string.game_activity_dialog_exit_game_title)
                    .setMessage(R.string.game_activity_dialog_exit_game_message)
                    .setCancelable(false)
                    .setPositiveButton(android.R.string.ok) { _: DialogInterface, _: Int ->
                        super.onBackPressed()
                    }
                    .setNegativeButton(android.R.string.cancel) { _: DialogInterface, _: Int -> }
            val alertDialog = builder.create()
            alertDialog.show()
        }
    }

Solution

  • Instead of handling back button pressing in your activity, you could do it in your fragments like this:

    activity?.onBackPressedDispatcher?.addCallBack(viewLifecycleOwner, true){
                //Navigate to other fragment
            }
    

    just implement Fragment ktx dependency

    implementation "androidx.fragment:fragment-ktx:1.2.5"
    

    For further information, check out this