How to create a button in Kotlin that opens a new activity (Android Studio)?

Nutters picture Nutters · Jul 14, 2017 · Viewed 50.7k times · Source

Hello I'm making an app using Android Studio and the Kotlin language and am having trouble getting my button to open a new activity. I have the button created in my xml file but I can't find the KOTLIN syntax of how to declare it in MainActivity.kt and how to create the OnClicklistener that would take me to the new activity. I have the new activity defined in the manifest as well I think I just need syntax help on how to actually switch from MainActivity.kt to secondActivity.kt. Any help is appreciated.

Answer

Jayanth picture Jayanth · Jul 14, 2017

You can add onclick event listener like below.

 button1.setOnClickListener(object: View.OnClickListener {
    override fun onClick(view: View): Unit {
        // Handler code here.
        val intent = Intent(context, DestActivity::class.java);
        startActivity(intent);
    }
})

Or you can use simplified form

   button1.setOnClickListener {
    // Handler code here.
    val intent = Intent(context, DestActivity::class.java)
    startActivity(intent);
   }