Reputation: 143
I am trying to link a function to the onClick property of a button in AndroidStudio but for some reason the system cannot identify the method that I coded.
The funny thing is that it works correctly when I code it in Java. In Kotlin it does not. I updated my Kotlin and checked its configuration but I cannot find the problem. My friend tried the same thing I did in a Linux computer and it worked for him. I have a Mac OS, I don't know if there is some extra configuration to take care of. Can anyone help me?
This is my simple activity:
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun sendMessage(view: View) {
}
}
This is the xml:
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:onClick="sendMessage"
android:text="@string/send_button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/editText"
app:layout_constraintTop_toTopOf="parent" />
In build.gradle I have:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
Error message:
Corresponding method handler 'public void sendMessage(android.view.View)' not found
The onClick attribute value should be the name of a method in this View's context to invoke when the view is clicked.
This name must correspond to a public method that takes exactly one parameter of type View. Must be a string value, using '\;' to escape characters such as '\n' or '\uxxxx' for a unicode character
Upvotes: 3
Views: 2717
Reputation: 143
It works now. I had to restart AndroidStudio. I still cannot add the function using the attributes window in the design tab but it works if I edit the XML directly.
Upvotes: 0
Reputation: 1314
Try to add
tools:context="com.somepackage.MainActivity"
to your top view in xml
Upvotes: 1