项目地址 https://github.com/webabcd/AndroidDemo
作者 webabcd

示例如下:

/kotlin/HelloWorld.kt

package com.webabcd.androiddemo.kotlin

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.webabcd.androiddemo.R
import kotlinx.android.synthetic.main.activity_kotlin_helloworld.*

class HelloWorld : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_kotlin_helloworld)

        button1.setOnClickListener {
            textView1.text = "hello world";
        }
    }
}

/layout/activity_kotlin_helloworld.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:andro
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAllCaps="false"
        android:text="click me"/>

</LinearLayout>

/kotlin/HelloWorld_Kotlin.kt

package com.webabcd.androiddemo.kotlin

class HelloWorld_Kotlin  {

    fun hello(message: String): String {
        return "hello: $message";
    }

    // kotlin 调用 java 的示例
    fun kotlinToJava(): String {
        var x = HelloWorld_Java();
        return x.hello("kotlin 调用 java")
    }
}

/kotlin/HelloWorld_Java.java

package com.webabcd.androiddemo.kotlin;

public class HelloWorld_Java {

    public String hello(String message) {
        return "hello: " + message;
    }

    // java 调用 kotlin 的示例
    public String javaToKotlin() {
        HelloWorld_Kotlin x = new HelloWorld_Kotlin();
        return x.hello("java 调用 kotlin");
    }
}

项目地址 https://github.com/webabcd/AndroidDemo
作者 webabcd

相关文章: