KTX 簡介

KTX 代表 Kotlin extension,有很多使用 Java 寫的 Library 是沒有辦法使用 Kotlin 獨有的語法,所以 Google 推出了 Kotlin 版本的 Library,如果你是用 Kotlin 開發,請儘量使用 KTX 版本的 Library

以下是我比較常用的 KTX。

Lifecycle KTX

Jetpack Release Note : Lifecycle

差別在於 Kotlin 版本的後面有 -ktx

用於 observe()

Declaring dependencies in Java

dependencies {
		...
		def lifecycle_version = "2.5.1"
		// ViewModel
    implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version"
    // LiveData
    implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle_version"

Declaring dependencies in Kotlin

dependencies {
    ...
    def lifecycle_version = "2.5.1"
    // ViewModel
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
    // LiveData
    implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
}

Sample code in Java

viewModel.counter.observe(this, Observer { count->
		infoText.text = count.toString()
})

備註:在 Java 中有個規定,如果一個方法同時使用 2 個 interface 做為參數,這兩個參數要同時使用函數型參數或非函數式參數,不可混用。(第一行代碼 3e P.547)

Sample code in Kotlin

viewModel.counter.observe(this) {count->
		infoText.text = count.toString()
}

Reference

Android KTX

Jetpack Release Note : Lifecycle

優先使用 KTX 庫 | MAD Skills

Last modified: 2023 年 3 月 8 日

Author

Comments

Write a Reply or Comment

Your email address will not be published.