我正在尝试将函数链接到 AndroidStudio 中按钮的 onClick 属性,但由于某种原因系统无法识别我编码的方法。
有趣的是,当我用 Java 编写代码时它可以正常工作。在 Kotlin 中它没有。我更新了我的 Kotlin 并检查了它的配置,但我找不到问题所在。我的 friend 尝试了我在 Linux 计算机上所做的同样的事情,并且对他有效。我有一个 Mac 操作系统,我不知道是否需要处理一些额外的配置。谁能帮帮我?
这是我的简单 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) {
}
}
这是 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" />
在 build.gradle 中我有:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
错误信息:
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
最佳答案
尝试添加
tools:context="com.somepackage.MainActivity"
到你的 xml 顶 View
关于android - 无法在 xml 定义的 Activity 中找到 onClick 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48610193/