Kotlin Android Button.onClickListener causing NoSuchMethodError

Viewed 2711

I think I've found a quirk of using kotlin for android, or there's some gap in my understanding of the syntax.

Trying to set an onClickListener for a button is throwing a NoSuchMethodError

Here's the code at fault

button.setOnClickListener(Button.OnClickListener {
            fun onClick(view: View){
                val intent : Intent = Intent(this,DetailActivity::class.java)
                if(obj is String) {
                    intent.putExtra("Topic", obj)
                }
                startActivity(intent)
            }
        })

And here's the stacktrace outputted

 java.lang.NoSuchMethodError: No static method OnClickListener(Lkotlin/jvm/functions/Function1;)Landroid/view/View$OnClickListener; in class Landroid/widget/Button; or its super classes (declaration of 'android.widget.Button' appears in /system/framework/framework.jar:classes2.dex)

Anyone know whats up?

3 Answers

You can try :

// case 1
button?.setOnClickListener { view -> 
   // handler here
}

// case 2
button?.setOnClickListener {
   // you can use keyword 'it' for use member view
   // handler here
}
Related