一手遮天 Android - kotlin: hello world

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

一手遮天 Android - kotlin: hello world

示例如下:

/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 {

            // 注:kotlin 语句结尾可以加分号,也可以不加分号(官方建议不加分号)
            textView1.append("hello world\n")

            // 用于演示 java 调用 kotlin
            textView1.append(HelloWorld_Java().javaToKotlin() + "\n")

            // 用于演示 kotlin 调用 java
            textView1.append(HelloWorld_Kotlin().kotlinToJava() + "\n")
        }
    }
}


/layout/activity_kotlin_helloworld.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/button1"
        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

posted @ 2021-05-31 12:04  webabcd  阅读(60)  评论(0编辑  收藏  举报