setOnClickListener not showing in basic Kotlin application

709 Views Asked by At

I'm really sorry if this question is at all redundant. I have read several posts and for some reason this issue does not seem to come up for anyone else. As such, I really hope it's solvable.

Long story short, I am a beginner in Android dev and I'm working with Kotlin. When I go to add "onClickListener" to a button, I get an error. The id is set to "button" so presumably I can just write "button.onClickListener {}" and begin my code. But for some reason this gives me and error.

button without method

As you can see here, I am not getting any methods provided for me off of "button"

The error I am getting is "kotlinx.android.main.activity_main.button?" (I'm not sure if that helps or not).

enter image description here

Thank you all so much for helping to get me started with Android.

EDIT

Based on feedback (THANK YOU SO MUCH BY THE WAY!!!) I clicked "ALT" and "Enter" and told the code to "import"

It brought in the line: "import kotlinx.android.synthetic.main.activity_main.*"

Unfortunately, I still do not get the "onClickListener" option though from intellisense. I believe I have this declared as a button in the "activity_main.xml" file but maybe not? Here are my screenshots:

enter image description here

3

There are 3 best solutions below

3
CommonsWare On BEST ANSWER

As you can see here, I am not getting any methods provided for me off of "button"

That is because the IDE does not recognize the button symbol. You have neither declared it nor imported it.

The error I am getting is "kotlinx.android.main.activity_main.button?"

That tooltip message not an error. The red highlight of button is an error. The underline means "hey, we are not sure what you mean by this symbol, but we have some imports that match!". The tooltip is indicating that if you press Alt-Enter (Windows/Linux), that it will add an import statement for kotlinx.android.main.activity_main.button to your list of import statements at the top of the Kotlin file. If button is a widget in your activity_main layout resource, then this will work and will give you the ability to set a click listener on it.

0
Farees Hussain On

Here the setOnClickListener is an extension function of Button

In your case, the 'button' must either be an id of a button widget in activity_main.xml or a variable declared using findViewById

0
Marcelo Vergara On

This way of binding views has changed. Please take a look at this codelab:

Use data binding to eliminate findViewById()

In previous versions, we could directly bind a view with kotlin code. Java didn't allow that. Something has changed.