編輯: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 由 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 的工具
寫過 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.*
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 上的專案。若閱讀時發現錯誤之處,歡迎指正。
Android 移動應用開發實戰經驗與技巧彙編
一、對話(Session)保持的解決方案 需求: 1、App 中使用 WebView 訪問具體網站的內容,但 App 與伺服器的溝通則使用 HttpURLConnecti
Android 7.0 Nougat 必看 11 項新功能
Android 7.0 Nougat 值得注意的新功能 Android 7.0 帶來多項貼近日常使用的改進,從多工、通知、省電到流量管理都有明顯變化。 1. 分割畫面
Android 架構演化之路:打造清晰可維護的代碼
大家好!過了好一陣子(其間我收到了大量讀者反饋),我決定是時候回到手機程序架構這個話題上了(這裡用 Android 代碼舉例),給大家另一個我認為不錯的解決方案。 開始之
Android 程式碼優化小技巧總整理
Android 效能優化並不一定都要從大型架構開始。許多時候,真正影響效能的是日常 Coding 中的小細節。以下整理幾項實用技巧,適合養成習慣,長期累積下來能改善程式效