Search code examples
androidkotlinandroid-widgetonclicklistener

I get an error (unresolved reference) in Android Studio when trying to use "new View.OnClickListener"


Im a beginner in Android Studio and have a school project where I have to create an login screen with password and username. When trying to follow some instructions online I get an error even though I have done the same as the instructor. Can you see what I have done wrong?

Example image


Solution

  • Your code is in Kotlin while the video you linked uses Java, so the error indicates that the onClickListener is not following Kotlin syntax properly.

    The equivalent in Kotlin is:

    logIn.setOnClickListener {
        // Do some work here
    }
    

    or

    logIn.setOnClickListener(object : View.OnClickListener {
        override fun onClick(view: View?) {
            // Do some work here
        }
    })
    

    Both will behave similarly. See alternative ways here.