How to open an activity programmatically in android using Kotlin
Today we will be going over a simple but useful piece of code that will follow you throughout your android career. This piece of code allows for you to open an activity while dismissing the previous activity. This will come in handy when working with any android project.
val intent = Intent(this, MovieNameQuiz::class.java)
startActivity(intent)
First the variable intent creates an intent that defines our current activity as this and our activity we will be opening is called MovieNameQuiz after the name of our class we are adding two colon’s followed by class.java which will call the java class instance of our Kotlin class. Android’s backbone is written in java so to open a view we have to get the java instance even though we are using Kotlin. Keep in mind we are taking advantage of the fact that Kotlin can call java classes, and java can call Kotlin classes. Kotlin runs on the JVM and that is why Kotlin even works on android. So we instantiated our class as a java class in order to open the activity. After creating our intent we pass it into a function called startActivity which will do the heavy lifting for us, and open the activity, while dismissing the previous activity. That’s it, hope you enjoyed this lesson on such a simple but interesting piece of code. I wrote this article because I seem to enjoy how Kotlin interacts with java in such a clean manner. Thanks for reading, stay tuned for more content.