简体   繁体   中英

Back button takes me to home screen instead of previous activity

I'm trying to add a login/register activities to my app, but I'm new to Android dev, so I'm not sure the right way I should be doing this.

The current logic I've got is:

App opens to MainActivity , MainActivity immediately launches the LoginActivity :

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        startActivity(
            Intent(baseContext, LoginActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)
        )
        finish()
    }
}

The LoginActivity has a login form and register/forgot password buttons. When the register button is pressed, I launch the RegisterActivity:

private fun handleRegisterClick() {
    startActivity(Intent(baseContext, RegisterActivity::class.java))
}

The problem I'm running into is when I press the Android back button in RegisterActivity , it takes me to the home screen instead of back to LoginActivity . Why is this happening?

因为您已经添加了.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)行, .addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)将其添加到Intent中,因此您将启动LoginActivity而不是当前所在的Activity。您对finish()进行的调用将确保不会MainActivity当您按下返回按钮时,该页面将导航回去。

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