Android-Kotlin- 按钮充当后退按钮

Android-Kotlin- button acting as back button

如何使屏幕按钮与 physical/virtual 后退按钮的作用相同? Kotlin,请不要 Java。我知道这只是复制一个函数,但这正是我的目标。
我正在尝试为 android 应用程序(Android Studio)学习 Kotlin 的基础知识,以满足我的好奇心,也许还可以为神经退行性疾病患者做些有益的事情。多亏了 Internet 的帮助,我得到了一个标准的 goto new activity 按钮可以正常工作(下面的示例),但我一直停留在那个按钮上。

val button: Button = findViewById(R.id.button_main_doccont)
    button.setOnClickListener {
        val intent = Intent(this, page_contact_doctor::class.java)
        startActivity(intent)
    }

您可以在 NavController 上调用 .navigateUp().popBackStack()

如果您没有对 NavController 的引用,您可以获取它。

在 Kotlin 中,您可以在 Fragment 中简单地执行

button.setOnClickListener {
   findNavController().navigateUp()
   // or
   findNavController().popBackStack()
}

否则您需要引用您正在导航的片段

button.setOnClickListener {
    fragment.findNavController().navigateUp()
    // or
    fragment.findNavController().popBackStack()
}

请注意 popBackStacknavigateUp 具有不同的语义。

popBackStack

的文档

Attempts to pop the controller's back stack. Analogous to when the user presses the system Back button when the associated navigation host has focus.

Returns: true if the stack was popped and the user has been navigated to another destination, false otherwise

navigateUp

的文档

Attempts to navigate up in the navigation hierarchy. Suitable for when the user presses the "Up" button marked with a left (or start)-facing arrow in the upper left (or starting) corner of the app UI. The intended behavior of Up differs from Back when the user did not reach the current destination from the application's own task. e.g. if the user is viewing a document or link in the current app in an activity hosted on another app's task where the user clicked the link. In this case the current activity (determined by the context used to create this NavController) will be finished and the user will be taken to an appropriate destination in this app on its own task.

Returns: true if navigation was successful, false otherwise

你不能在 Activity 上直接调用 onBackPressed() 吗?这与按下物理后退按钮的效果完全相同。