Follow this tutorial: Android - Start Another Activity if I made MainActivity.java button OnClick attribute has the sendMessage() method.

但如果我制作了MainActivity.kt按钮OnClick属性,则没有任何显示,只有none.

这是Android Studio 3的漏洞还是我错过了Kotlin的一些东西?

Java Main活动:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    /** Called when the user taps the Send button */
    public void sendMessage(View view) {
        // Do something in response to button
    }

}

Kotlin mainActivity:

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    /** Called when the user taps the Send button  */
    fun sendMessage(view: View) {
        // Do something in response to button
    }
}

OnClick attribute

XML布局(Java和Kotlin项目相同)

    <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="ir.bigbang.vahid.myapplication.MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        tools:layout_editor_absoluteX="148dp"
        tools:layout_editor_absoluteY="81dp" />
</android.support.constraint.ConstraintLayout>

推荐答案

设计师似乎还不支持Kotlin .以下是一些解决方案:

XML (Not Recommended)

Add the following line to your Button tag. This is exactly what the designer will do.

android:onClick="sendMessage"

Old Fashion

不需要添加任何内容.

val button = findViewById<Button>(R.id.Button)
button.setOnClickListener {

}

kotlin-android-extensions (Recommended)

apply plugin: "kotlin-android-extensions"加到您的构建中.gradle

// button is the Button id
button.setOnClickListener {

}

Kotlin相关问答推荐

在KMM合成多平台中创建特定于平台的视图

列表在 android WebView 中没有正确迭代

为什么 Kotlin 在将协变类型参数转换为不变类型参数时会产生 Unchecked Cast 警告?

通用接口继承

如何处理基于枚举提前返回的 forEach 循环,Kotlin 中的一条路径除外

测试协程和线程之间的差异,我在kotlin中使用线程时无法得到OOM错误

关于 Kotlin 函数类型转换的问题

为什么 Kotlin 扩展运算符在传递原始可变参数时需要 toTypedArray()?

Kotlin 中多个 init 块的用例?

如何在主线程上使用 Kotlin 协程 await()

验证和 DDD - kotlin 数据类

Kotlin JVM 和 Kotlin Native 有什么区别?

如何在kotlin语言中将字符转换为ascii值

如何获取Kotlin中变量的名称?

在 Kotlin 中创建 Spinner 时,如何在 Fragment 中的旋转屏幕上修复指定为非空的参数为空?

Lint 错误:可疑的相等判断:在 Object DiffUtilEquals 中未实现 equals()

Android studio 4.0 新更新版本说 Kotlin 与这个新版本不兼容

从 java 活动 *.java 启动 kotlin 活动 *.kt?

Kotlin中默认导入哪些包/函数?

是否可以在不使用class的情况下将 Mockito 与 Kotlin 一起使用?