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 的基本語法。佈局