简体   繁体   中英

How to create a correct navigation between screens on android

I've looked enough and I did not find a solution to my problem. I have not found any solution in the android documentation (or maybe I did not understand). I have a simple android app, and when I press the back key, in maiActivity, the application can return to a previous screen when the expected behavior is to exit the application. I await a suggestion.

Just put this in your MainActivity :

override fun onBackPressed() {
    super.onBackPressed()
    finish()
}

Additionally, if you want to add an AlertDialog for the user to ask confirmation before exiting:

override fun onBackPressed() {
    AlertDialog.Builder(this)
        .setTitle("Exit Confirmation")
        .setMessage("Are you sure you want to exit?")
        .setNegativeButton(android.R.string.no, null)
        .setPositiveButton(android.R.string.yes) 
            { _, _ -> super.onBackPressed() }
        .create()
        .show()
    }
}

I guess I've known what you want to do. The correct operation is: when you jump to a activity by startActivity(yourIntent) , you should add finish() if you don't need the current activity any more. If you didn't add finish() , the default behavior is back to previous screen when you click back button in new activity.

You should manage your activity stack well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM