Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 資訊

優雅地用 Kotlin 開發 Android:Anko 實戰與對照 Java 的寫法

編輯:Android 資訊

寫在前面

上一篇我們看過 Kotlin 的優勢與基本語法,這次直接進到實作:如何在 Android 專案裡把 Kotlin 用起來,並與傳統 Java 寫法並排對照,你會很直接地感受到差異在哪裡。

環境設定

專案層級的 build.gradle:

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

dependencies {
    classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.1.1'
}

App 層級的 build.gradle:

compile 'org.jetbrains.kotlin:kotlin-stdlib:1.1.1'
compile 'org.jetbrains.anko:anko-sdk25:0.10.0-beta-1' // sdk15, sdk19, sdk21, sdk23 亦可用
compile 'org.jetbrains.anko:anko-appcompat-v7:0.10.0-beta-1'

Anko 是什麼

上面的設定裡出現了 Anko 的依賴。Anko 由 JetBrains 開發——也就是 Kotlin 的作者、IntelliJ IDEA 的開發者,Android Studio 同樣建立在 IDEA 之上。Anko 是官方提供、讓 Android 開發更快更簡單的 Kotlin 函式庫,同時能讓程式碼更簡潔易讀,主要分成幾塊:

Anko Commons: 大量關於 Intent、Dialog、日誌等的輔助函式
Anko Layouts: 快速且型別安全地撰寫動態版面
Anko SQLite: Android SQLite 的查詢 DSL 與解析器集合
Anko Coroutines: 基於 kotlinx.coroutines 的工具

再也不用 findViewById

寫過 Android 的人都知道 findViewById 有多耗工,還得先宣告變數、再轉型:

TextView username;
username = (TextView) findViewById(R.id.user);
username.setText("我是一個TextView");

有人會說用 ButterKnife 這類註解庫就不必寫了:

@BindView(R.id.user) TextView username;
username.setText("我是一個TextView");

確實省下一些工,但還不夠極簡。最極簡的寫法是直接對 id 為 user 的元件赋值:

user.text = "我是一個TextView"

user 就是版面檔裡宣告的 id,.text 等同 setText()。在 Kotlin 中我們看不到 Java 的 set/get 方法了。要使用這個特性,除了 gradle 中的 kotlin-android-extensions 外掛,還需要匯入對應的版面:

// activity_login 就是我們的版面檔
import kotlinx.android.synthetic.main.activity_login.*

Anko Layout:用 DSL 寫版面

XML 寫版面有幾個先天限制:非型別安全、非空安全、解析 XML 會消耗較多 CPU 與電力。Anko Layout 用 DSL 動態建立 UI,比用 Java 動態建立版面簡潔得多,而且保有與 XML 一致的層級結構,可讀性很好。

verticalLayout {
    val textView = textView("我是一個TextView")
    val name = editText("EditText")
    button("Button") {
        onClick { toast("${name.text}!") }
    }
}

在 onCreate 中拿掉 setContentView,改放這段程式碼,就會得到一個垂直 LinearLayout,裡頭依序是 TextView、EditText 與 Button,而 Button 有點擊事件,會把輸入框內容以 Toast 顯示。

屬性的設定邏輯與 XML 完全一致,所以下面這段不需要多解釋你也看得懂:

val textView = textView("我是一個TextView") {
    textSize = sp(17).toFloat()
    textColor = context.resources.getColor(R.color.red)
}.lparams {
    margin = dip(10)
    height = dip(40)
    width = matchParent
}

如果把建立 UI 的程式碼直接寫在 onCreate 裡覺得太長,還可以另開內部類別實作 AnkoComponent 介面,並覆寫 createView:

inner class UI : AnkoComponent<LoginActivity> {
    override fun createView(ui: AnkoContext<LoginActivity>): View {
        return with(ui) {
            verticalLayout {
                val textView = textView("我是一個TextView") {
                    textSize = sp(17).toFloat()
                    textColor = context.resources.getColor(R.color.red)
                }.lparams {
                    margin = dip(10)
                    height = dip(40)
                    width = matchParent
                }
                val name = editText("EditText")
                button("Button") {
                    onClick { view -> toast("Hello, ${name.text}!") }
                }
            }
        }
    }
}

然後在 onCreate 中加一行就能掛上版面:

UI().setContentView(this@LoginActivity)

編譯執行後,效果與 XML 寫的完全一樣。這種 DSL 寫法確實易讀也好上手。上面的 dip(10) 是把 10dp 轉成像素的擴充函式;讀過 Anko 原始碼會發現它大量使用擴充函式,這正是 Kotlin 的強項之一:

inline fun View.dip(value: Int): Int = context.dip(value)

fun Context.dip(value: Int): Int = (value * resources.displayMetrics.density).toInt()

resources.displayMetrics.density 與 Java 的 getResources().getDisplayMetrics().density 效果相同,但讀起來舒服多了。

Button 的點擊事件支援 lambda。想顯示 Toast,只要 toast("內容"),這也是擴充函式:

inline fun AnkoContext<*>.toast(message: CharSequence) = ctx.toast(message)

fun Context.toast(message: CharSequence) =
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show()

建立 Dialog 同樣簡單:

alert("我是Dialog") {
    yesButton { toast("yes") }
    noButton { toast("no") }
}.show()

最後再看一段——效果等同 AsyncTask,但簡潔程度完全不在同一個量級:

doAsync {
    // 背景執行
    uiThread {
        // 回到 UI 執行緒
        toast("線程${Thread.currentThread().name}")
    }
}

用 Kotlin 開發 Android 一段時間之後,你會發現程式碼量真的少了很多,而更多用法值得自己往下挖。

實作一個登入介面

結構並不複雜,用偽程式碼表示:

<LinearLayout>
    <ImageView/>
    <LinearLayout>
        <ImageView/><EditText 帳號/>
    </LinearLayout>
    <LinearLayout>
        <ImageView/><EditText 密碼/>
    </LinearLayout>
    <Button 登錄/>
    <LinearLayout>
        <CheckBox 記住密碼/><TextView 隱私協議/>
    </LinearLayout>
    <TextView/>
</LinearLayout>

XML 版本就不佔篇幅了,直接看 Anko 的 Kotlin 實作:

lateinit var et_account: EditText
lateinit var et_password: EditText

inner class LoginUi : AnkoComponent<LoginActivity> {
    override fun createView(ui: AnkoContext<LoginActivity>) = with(ui) {
        verticalLayout {
            backgroundColor = context.resources.getColor(android.R.color.white)
            gravity = Gravity.CENTER_HORIZONTAL
            imageView(R.mipmap.ic_launcher).lparams {
                width = dip(100)
                height = dip(100)
                topMargin = dip(64)
            }
            linearLayout {
                gravity = Gravity.CENTER_VERTICAL
                orientation = HORIZONTAL
                backgroundResource = R.drawable.bg_frame_corner
                imageView {
                    image = resources.getDrawable(R.mipmap.ic_username)
                }.lparams(width = wrapContent, height = wrapContent) {
                    leftMargin = dip(12)
                    rightMargin = dip(15)
                }
                et_account = editText {
                    hint = "登錄賬戶"
                    hintTextColor = Color.parseColor("#666666")
                    textSize = 16f
                    background = null
                }
            }.lparams(width = dip(300), height = dip(40)) {
                topMargin = dip(45)
            }
            linearLayout {
                orientation = HORIZONTAL
                backgroundResource = R.drawable.bg_frame_corner
                gravity = Gravity.CENTER_VERTICAL
                imageView {
                    image = resources.getDrawable(R.mipmap.ic_password)
                }.lparams {
                    leftMargin = dip(12)
                    rightMargin = dip(15)
                }
                et_password = editText {
                    hint = "登錄密碼"
                    hintTextColor = Color.parseColor("#666666")
                    textSize = 16f
                    background = null
                }
            }.lparams {
                width = dip(300)
                height = dip(40)
                topMargin = dip(10)
            }
            button("登錄") {
                gravity = Gravity.CENTER
                background = resources.getDrawable(R.drawable.bg_login_btn)
                textColor = Color.parseColor("#ffffff")
                onClick {
                    if (et_account.text.toString().isNotEmpty() &&
                            et_password.text.toString().isNotEmpty()) {
                        startActivity<MainActivity>()
                    } else {
                        toast("請輸入賬戶或者密碼")
                    }
                }
            }.lparams(width = dip(300), height = dip(44)) {
                topMargin = dip(18)
            }
            linearLayout {
                orientation = HORIZONTAL
                gravity = Gravity.CENTER_VERTICAL
                checkBox("記住密碼") {
                    textColor = Color.parseColor("#666666")
                    textSize = 16f
                    leftPadding = dip(5)
                }
                textView("隱私協議") {
                    textColor = Color.parseColor("#1783e3")
                    gravity = Gravity.RIGHT
                    textSize = 16f
                }.lparams(width = matchParent)
            }.lparams(width = dip(300)) {
                topMargin = dip(18)
            }
            textView("Copyright © Code4Android") {
                textSize = 14f
                gravity = Gravity.CENTER or Gravity.BOTTOM
            }.lparams {
                bottomMargin = dip(35)
                weight = 1f
            }
        }
    }
}

即使現在還不會寫,這段程式碼也讀得懂。登入按鈕上掛了跳轉 MainActivity 的事件,startActivity 的尖括號裡放目標 Activity;要傳值就直接寫在括號中:

startActivity<MainActivity>(
        "account" to et_account.text.toString(),
        "password" to et_password.text.toString())

Anko 的能力遠不止於此,有興趣深入可以去看 GitHub 上的專案。若閱讀時發現錯誤之處,歡迎指正。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved