How to navigate in Android & Kotlin
Navigation comes up frequently in any standard mobile application.
In the android ecosystem, navigation is done with the concept of intents.
Intent will navigate from one activity to the next. We can also attach extras to the intent to carry information between activities.
// navigating to the next activity
val intent = Intent(this, SecondActivity::class.java)
intent.putExtra("stuff", 1)
startActivity(intent)
In the above code snippet, a new intent is created using the SecondActivity as the destination. We also put an extra with “stuff” as key and 1 as the value.
StartActivity function is what actually tells android to navigate to the next activity. In the next activity we can access the extra that was passed from the previous activity.
class SecondActivity:Activity(){
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val stuff = intent.getIntExtra("stuff", 0)
}
}
In the above code snippet, we were able to access the int extra from the intent.
That is a basic summary of how to navigate between activities using intents and extras in kotlin with android.