How to Change Android activity
Published in
1 min readAug 5, 2020
There are two ways to switch activity screens on Android. Switching screens is all the same, but one simply switches, while the other can execute code when it comes back.
startActivity( )
Simply switch to another activity
val intent = Intent(this, SecondActivity::class.java)
startActivity(intent)
StartActivityForResult ( )
Switch to another activity. And you can catch it when you get back.
private val REQUEST_CODE_SecondActivity = 51val intent = Intent(this, SecondActivity::class.java)
startActivityForResult(intent, REQUEST_CODE_SecondActivity)
To detect when you return to an existing screen
If you switched screen by startActivityForResult( ), you can catch it from onActivityResult( ) when you return to your existing activity.
You can use the requestCode and resultCode for which screen you sent and what results you received.
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == REQUEST_CODE_SecondActivity) {
tv_returnText.text = "I'm back"
} else {
super.onActivityResult(requestCode, resultCode, data)
}
}