Home > Software design >  Android-Kotlin- button acting as back button
Android-Kotlin- button acting as back button

Time:01-07

How do I make an on-screen button act in the same way as a physical/virtual back button? Kotlin, not Java please. I know this is just duplicating a function, but this is precisely my goal here.
I'm trying to learn basics of Kotlin for android apps (Android Studio), to satisfy my curiosity and maybe also do something good for neurodegenrative disease patients. Thanks to Internet help, I got a standard, goto new activity button working (example below), but I'm stuck on that one.

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

CodePudding user response:

You would call either .navigateUp() or .popBackStack() on the NavController.

If you don't have a reference to the NavController, you can obtain it.

In Kotlin, inside a Fragment you can simply do

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

Otherwise you need a reference to the fragment you are navigating from

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

Note that popBackStack and navigateUp have different semantics.

Docs for 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

Docs for 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

CodePudding user response:

Can't you just call onBackPressed() on the Activity? That would do exactly the same thing as pressing the physical BACK button.

  •  Tags:  
  • Related