Google 在 2017 年的 I/O 大会上宣布支持使用 Kotlin 语言来开发 Android 应用程序,和 Java 同为一级开发语言。而今年的 I/O大会上, Google 正式宣布,Kotlin 将由一级开发语言转为第一开发语言,将来 Google 提供的 API 都会优先以 Kotlin 为准。固然 Java 和 C++ 开发也会继续支持下去,暂时尚未放弃 Java 的时间表。android
据有关统计说,目前已有超过 50% 的专业 Android 开发者选择使用 Kotlin,而且 Kotlin 目前是 Github 中上升最快的编程语言。编程
从谷歌的推广力度及目前的使用程度来看,使用 Kotlin 开发已成为趋势,因此如今开始一块儿学习吧!缓存
相关资料:
官方网站
官方学习文档
Kotlin 中文网站bash
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
复制代码
dependencies {
classpath 'com.android.tools.build:gradle:3.4.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
复制代码
//第一个就是支持 Kotlin 的插件
apply plugin: 'kotlin-android'
//使用第二个插件,今后告别 findViewById 的困扰
apply plugin: 'kotlin-android-extensions'
复制代码
Kotlin Android Extensions 是 Kotlin 的一个插件,它包含在普通的那个插件中,这就容许以惊人的无缝方式从 Activity,Fragment 和 View 中恢复 View。app
该插件将生成一些额外的代码,容许你访问布局 XML 的 View,就像它们是在布局中定义的属性同样,你可使用 id 的名称。编程语言
它还构建本地视图缓存。因此首次使用一个属性时,它会作一个普通的 findViewById。而接下来,View 则是从缓存中恢复,所以访问速度更快。ide
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/mTvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</android.support.constraint.ConstraintLayout>
复制代码
mTvName.text = "nice to meet you"
复制代码
之因此能够这样使用,由于 Studio 导入了 View 的合成属性 (其中 activity_main 为布局文件名)函数
import kotlinx.android.synthetic.main.activity_main.*
复制代码
是否是瞬间爽翻了,不再用 findViewById 了,这能够节省很多时间,代码量也减小了不少,这也是 Kotlin 的一大优点。工具
本小节就介绍到这里,下一小节咱们会学习 Kotlin 的基本语法。布局