創建項目並在根目錄 build.gradle 配置
buildscript {
ext.kotlin_version ='1.3.11'
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
在 app 中的 build.gradle 配置
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
}
然後編譯成功即可使用。
創建Activity
選擇語言爲Kotlin
佈局文件寫法不變
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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=".ui.KotlinActivity">
<TextView
android:id="@+id/tv_text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="hello"
/>
</LinearLayout>
Activity中可以直接通過id去賦值,省去了findViewById的操作。
package com.example.textkt.ui
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import com.example.textkt.R
import kotlinx.android.synthetic.main.activity_kotlin.*
class KotlinActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_kotlin)
tv_text.text = "Kotlin NB"
}
}
運行效果