检测 onBackPressed 是否会破坏 Activity?

Detect if onBackPressed will destroy an Activity?

我正在尝试实现一个确认用户想要销毁 activity 的对话框。查看 few other ,似乎我可以覆盖 onBackPressed() 功能来添加此对话框。但是,我的应用程序在同一个 activity 中的片段之间进行导航,因此“后退”按钮可能在片段之间导航并且实际上不会破坏 activity。我的方法是朝着正确的方向发展还是存在根本性的缺陷?如果是惯用的,下一个问题是如何确定activity是否会被销毁?

    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()
        }
    }

您可以像这样在您的片段中处理后退按钮,而不是在您的 activity 中按下:

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

只需实现 Fragment ktx 依赖

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

有关更多信息,请查看 this