[英]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). 我在android文档中没有找到任何解决方案(或者我听不懂)。 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. 我有一个简单的android应用程序,当我按maiActivity中的返回键时,当预期的行为是退出应用程序时,应用程序可以返回到上一个屏幕。 I await a suggestion. 我等待一个建议。
Just put this in your MainActivity
: 只需将其放在您的MainActivity
:
override fun onBackPressed() {
super.onBackPressed()
finish()
}
Additionally, if you want to add an AlertDialog
for the user to ask confirmation before exiting: 另外,如果要添加AlertDialog
以便用户在退出前询问确认:
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. 正确的操作是:当您通过startActivity(yourIntent)
跳转到活动时,如果不再需要当前活动,则应添加finish()
。 If you didn't add finish()
, the default behavior is back to previous screen when you click back button in new activity. 如果未添加finish()
,则在新活动中单击“后退”按钮时,默认行为将返回上一屏幕。
You should manage your activity stack well. 您应该很好地管理活动堆栈。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.