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

Viewed 61682

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.

8 Answers
// In your method `fun onCreate(savedInstanceState: Bundle?)` add this.

    your_btn_id.setOnClickListener{

                val intent = Intent(this, yourpagename::class.java)
                startActivity(intent)
            }

// till now if it doesn't work then, check if these two files are added or not,

    import android.content.Intent
    import kotlinx.android.synthetic.main.activity_otp.*

// Hope that it would work.

You can create a generic method to launch any Activity

  inline fun<reified T> launchActivity(){
    val intent = Intent(this, T::class.java)
    startActivity(intent)
}

And can be use like

 button1.setOnClickListener {
      launchActivity<AnyActivity>()
}

To get More details about reified Go to Here

You can simply declare your button in the main activity as below:

val button = findViewById<Button>(R.id.button)
        button.setOnClickListener(this);

And in the clicklistener start the new activity:

override fun onClick(p0: View?) {
        val intent = Intent(this, activity::class.java)
        startActivity(intent)
    }

I had to add first id 'kotlin-android-extensions' inside of plugins in build.gradle. after that in OnCreate Button.setOnClickListener { }

Kotlin

Make sure the item is inside the OnCreate method. Edit the XML file (res/layout folder) and create button:

<Button
    android:id="@+id/button"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:text="Press me"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"
    android:layout_marginStart="40dp"
    android:layout_marginEnd="40dp"
    android:layout_marginBottom="40dp"
    />

Next is main activity class:

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val button: Button = findViewById(R.id.button)
        button.setOnClickListener {
           
           val intent = Intent(context, NewActivity::class.java)
           startActivity(intent);
        }
    }
}
Related