gpt4 book ai didi

kotlin - 如果事件是用 Kotlin 编写的,则按钮 onClick 属性为无

转载 作者:IT老高 更新时间:2023-10-28 13:28:45 28 4
gpt4 key购买 nike

按照本教程进行操作:Android - Start Another Activity如果我做了 MainActivity.java 按钮 OnClick 属性有 sendMessage() 方法。

但是如果我制作了 MainActivity.kt 按钮 OnClick 属性没有什么可显示的,只是一个 none

这是 Android Studio 3 的错误还是我错过了 Kotlin 的某些内容?

Java 主事件:

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 主事件:

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(不推荐)

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

android:onClick="sendMessage"

旧时尚

不需要添加任何东西。

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

}

kotlin-android-extensions(推荐)

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

// button is the Button id
button.setOnClickListener {

}

关于kotlin - 如果事件是用 Kotlin 编写的,则按钮 onClick 属性为无,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46970565/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com