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

Button in layout xml file

        <Button
            android:id="@+id/btn_start_new_activity"
            android:text="New Activity"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

For declaring it in the Kotlin Activity file

var btn_new_activity = findViewById(R.id.btn_start_new_activity) as Button

Set Onclicklistener to the button, to start new activity when button is clicked

    btn_new_activity.setOnClickListener {
        val intent = Intent(context, NewActivity::class.java)
        startActivity(intent);
    }

Reference: Android Studio Tutorial - https://www.youtube.com/watch?v=7AcIGyugR7M


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);
   }