11

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.

Nutters
  • 797
  • 2
  • 6
  • 12

8 Answers8

20

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);
   }
Jayanth
  • 5,954
  • 3
  • 21
  • 38
  • 1
    Thanks for the response, however, if I copy paste the above code into my MainActivity.kt file pretty much the entire thing is covered in error messages saying that startActivity, Intent, and context are all unresolved references and that final/intent have variables expected. It also says on the first line that a member declaration is expected. Any idea what is wrong? Edit: On top of that, if I use the simplified form it says that the function declaration no longer has a name. – Nutters Jul 14 '17 at 17:23
  • I assumed that your button variable name is `button1` and `context` variable has the activity context (else just use `this` or `YourClassName.this` ). – Jayanth Jul 14 '17 at 17:39
  • 2
    add this code inside onCreate() and after you get the reference of button1 via findViewById() – Jayanth Jul 14 '17 at 17:40
  • thank you very much for the help so far, I still have a few issues though, I have gotten the reference of button1 and put everything inside of onCreate() but the line final Intent intent = new Intent(this, secondActivity.class); says that final is still an unresolved reference and expects a variable, that Intent expects a variable (am I supposed to use secondActivity as the intent here or something?), that "new" is an unresolved reference, and that secondActivity is an unexpected token. – Nutters Jul 14 '17 at 18:27
  • Thank you! Down to one final error saying that java is an unresolved reference in "secondActivity::class.java", I also tried replacing it with class.kotlin but that doesn't seem to do the trick either. – Nutters Jul 14 '17 at 18:55
  • class names are case sensitive – Jayanth Jul 14 '17 at 19:05
  • "secondActivity" is how I named my second one so I don't think it should be a capitalization issue. – Nutters Jul 14 '17 at 19:07
  • Is that file named same? – Jayanth Jul 14 '17 at 19:10
  • http://imgur.com/a/zQGi9 This is a picture of what I have which might be helpful, the file name of the other activity is the same yes. – Nutters Jul 14 '17 at 19:17
6

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

arjun
  • 1,645
  • 1
  • 19
  • 19
2

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>() }
    }
  • Thanks! I will look into this as well, I would like to figure out how to do it the original way at first but I will for sure look into that for later projects. Cheers. – Nutters Jul 14 '17 at 18:33
  • It is deprecated. Use [splitties](https://github.com/LouisCAD/Splitties) – Vlad Jan 09 '20 at 07:47
2
// 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.

Raghib Arshi
  • 717
  • 8
  • 12
1

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

shahid17june
  • 1,441
  • 1
  • 10
  • 15
1

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);
        }
    }
}
J A S K I E R
  • 1,976
  • 3
  • 24
  • 42
0

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)
    }
Nikitha
  • 49
  • 5
0

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