如果在Kotlin中写入活动,则按钮onClick属性为none

Vah*_*hid 26 kotlin android-studio-3.0

按照本教程: Android -如果我使MainActivity.java按钮OnClick属性具有该sendMessage()方法,则启动另一个活动.

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

这是一个Android Studio 3错误还是我错过了Kotlin的东西?

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
    }

}
Run Code Online (Sandbox Code Playgroud)

Kotlin主要活动:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

OnClick属性

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>
Run Code Online (Sandbox Code Playgroud)

Jos*_*hua 33

看起来设计师还不支持Kotlin.这是一些解决方案:

XML(不推荐)

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

android:onClick="sendMessage"
Run Code Online (Sandbox Code Playgroud)

旧的时尚

无需添加任何内容.

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

}
Run Code Online (Sandbox Code Playgroud)

kotlin-android-extensions(推荐)

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

// button is the Button id
button.setOnClickListener {

}
Run Code Online (Sandbox Code Playgroud)

  • 好的,我是通过XML(android:onClick ="sendMessage")完成的,这很有效.但为什么不推荐这个? (7认同)
  • @Freek在我看来,XML应该仅关于如何查看布局。编程逻辑应该在代码中。当其他人读取您的代码时,他们将不知道在XML中添加了侦听器。另外,在重用XML时,必须确保在两个活动中都必须存在该功能。与其他方式相比,用XML编写侦听器没有任何好处。因此不建议使用。 (2认同)

Md.*_*rim 6

你的代码会是这样的:

button.setOnClickListener(){
            Toast.makeText(this@MainActivity, "Its toast!", Toast.LENGTH_SHORT).show();
        }
Run Code Online (Sandbox Code Playgroud)

这里导入将

import kotlinx.android.synthetic.main. activity_main.*
Run Code Online (Sandbox Code Playgroud)

这里的“按钮”是 .xml 文件中该按钮的 id。这里的优点是不需要在你的 java 类中创建 Button 对象。

  • 这是一种更自然的 Kotlin 方式,再加上不必获取按钮对象很酷 (2认同)