How do I create a button in Kotlin that opens a new activity (Android Studio)?
Hi I'm making an application using Android Studio and Kotlin language and I am having trouble getting my button to open a new activity. I have a button created in my XML file, but I cannot find the KOTLIN syntax, how to declare it in MainActivity.kt, and how to create an OnClicklistener that will take me to a new activity. I have a new Activity defined in the manifest and I think I just need some syntactic help on how to actually switch from MainActivity.kt to secondActivity.kt. Any help is appreciated.
source to share
You can add an event listener onclick
as shown 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 a simplified form
button1.setOnClickListener {
// Handler code here.
val intent = Intent(context, DestActivity::class.java)
startActivity(intent);
}
source to share
I recommend using the Anko extension for Kotlin https://github.com/Kotlin/anko . This allows intent (and more) to be used in the shortest possible way. In your case, it would be:
button {
onClick { startActivity<SecondActivity>() }
}
source to share
Button in XML file layout
<Button
android:id="@+id/btn_start_new_activity"
android:text="New Activity"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
To declare it in the Kotlin activity file
var btn_new_activity = findViewById(R.id.btn_start_new_activity) as Button
Set an Onclicklistener on the button to start a new action when the button is clicked
btn_new_activity.setOnClickListener {
val intent = Intent(context, NewActivity::class.java)
startActivity(intent);
}
Ref: Android Studio Tutorial - https://www.youtube.com/watch?v=7AcIGyugR7M
source to share