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)
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)
你的代码会是这样的:
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 对象。
归档时间: |
|
查看次数: |
40823 次 |
最近记录: |