Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 217
Nutters Avatar asked Jul 14 '17 17:07

Nutters


Video Answer


4 Answers

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);
   }
like image 91
Jayanth Avatar answered Oct 17 '22 06:10

Jayanth


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

like image 28
shahid17june Avatar answered Oct 03 '22 20:10

shahid17june


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

like image 6
Mallikarjun M Avatar answered Oct 17 '22 05:10

Mallikarjun M


I recommend you use the Anko - extension for Kotlin https://github.com/Kotlin/anko. It let you use intent(and more other things) the shortest way. In your case it`ll be:

button {
        onClick { startActivity<SecondActivity>() }
    }
like image 3
Kirill Bitkov Avatar answered Oct 17 '22 06:10

Kirill Bitkov