一、安装kotlin插件
二、导入Kotlin的核心库及其扩展库Anko库
1、在项目根目录下的build.gradle文件中指定kotlin插件的版本及路径
buildscript {
ext.kotlin_version = "1.1.2-3"
ext.anko_version = "0.9"
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.3'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"
}
}
...
2、在module的build.gradle文件中将kotlin插件编译进来
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 25
buildToolsVersion "25.0.3"
...
}
dependencies {
...
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
compile "org.jetbrains.anko:anko-common:$anko_version"
}
三、使用
新建Kotlin的Activity,命名KotlinActivity,布局文件activity_kotlin。
布局文件:
<?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">
<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="button"/>
<TextView
android:id="@+id/textview"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
KotlinActivity代码:
class KotlinActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_kotlin)
//按钮的点击事件,给textview赋值
btn.setOnClickListener { textview.text = "早上好" }
}
}
上述代码中,因为导包的时候加了下面这句,所以布局里所有控件再也不用findViewById实例化了,可直接拿控件id当实例化后的控件本身使用。
import kotlinx.android.synthetic.main.activity_kotlin.*
四、补充
将java代码转为kotlin代码,执行code–> Convert Java File to Kotlin File,如图:
这样,当遇到一些kotlin语法不熟的地方,可先用java代码写出来,再传为kotlin代码。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)