如果用Kotlin编写的活动,则按钮onClick属性为none [英] Button onClick attribute is none if activity written in Kotlin

查看:195
本文介绍了如果用Kotlin编写的活动,则按钮onClick属性为none的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请遵循本教程: Android-启动另一个活动我使MainActivity.java按钮的OnClick属性具有sendMessage()方法.

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

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

But if I made MainActivity.kt button OnClick attribute has nothing to show, just a none.

这是Android Studio 3的bug还是我错过了Kotlin的东西?

Is this an Android Studio 3 bug or I missed something for Kotlin?

Java mainActivity:

Java mainActivity:

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:

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
    }
}

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

XML layout (Java and Kotlin project are the same)

    <?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.以下是一些解决方案:

It seems like the designer does not support Kotlin yet. Here are some solution:

XML(不推荐)

将以下行添加到您的Button标记中.这正是设计师要做的.

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

android:onClick="sendMessage"

旧时尚

无需添加任何内容.

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

}

kotlin-android-extensions(推荐)

apply plugin: "kotlin-android-extensions"添加到您的build.gradle

Add apply plugin: "kotlin-android-extensions" to your build.gradle

// button is the Button id
button.setOnClickListener {

}

这篇关于如果用Kotlin编写的活动,则按钮onClick属性为none的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆