Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I can't use setOnClickListener in Kotlin

i am trying to set up a second page for my android app but when i try to do it my setOnClickListener is red here is the code part:

    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    val MainActivity2 = findViewById<Button>(R.id.button)
    Button.setOnClickListener {
        val Intent = Intent(this,MainActivity2::class.java)
        startActivity(Intent)
    }

Does anyone know why the setOnClickListener is red ? (the Button. is not red)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You have assigned your button into the variable named MainActivity2. You do not currently have a variable named Button I assume.
You need to use

MainActivity2.setOnClickListener
{code here}
instead

Another way for you to do the same thing:

In your xml file for your Button element, you can add an onClicked attribute.
Example:

<Button
    ...
    android:onClick="deleteAll"
    android:clickable="true"/>

In your kotlin file which uses that xml file for the view:

fun deleteAll(view: View) {
    doSomething()
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading