问题描述
请遵循本教程: 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!