編輯:關於 Android 開發
作者:Antonio Leiva 時間:2016 年 12 月 12 日 原文:https://antonioleiva.com/kotlin-android-extensions/

日復一日地寫 findViewById,大概每個 Android 開發者都會感到疲憊。有些人乾脆轉投 ButterKnife 這類依賴注入庫。如果你也屬於這一群人,那麼 Kotlin 的 Android 擴展插件一定會讓你愛不釋手。
它是 Kotlin 官方插件家族中的一員,能無縫地把 Activity、Fragment 以及自定義 View 中的視圖引用直接暴露出來,讓 XML 裡的 id 變成可以直接調用的屬性。
使用插件並不需要額外寫依賴,只要在 Android 模塊的 build.gradle 中追加一行 apply:
apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions'
添加完這幾行,一切就準備就緒了。
啟用插件之後,訪問視圖變得跟在 XML 中按 id 定義屬性一樣直觀。
假設你有這樣一份布局:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/welcomeMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!"/>
</FrameLayout>
這個 TextView 的 id 是 welcomeMessage。那麼在 MainActivity 裡,你只需要這樣寫:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
welcomeMessage.text = "Hello Kotlin!"
}
為了讓這行代碼生效,需要補上一句 import,好在 IDE 通常會自動幫你補齊:
import kotlinx.android.synthetic.main.activity_main.*
更貼心的是,插件生成的代碼自帶視圖緩存,同一個 id 第二次訪問時不再觸發額外的查找開銷。
考慮這樣一份 item 布局:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/itemImage"
android:layout_width="match_parent"
android:layout_height="200dp"/>
<TextView
android:id="@+id/itemTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
當你把這份布局交給 Adapter 使用時,可以直接從 itemView 一路點到子視圖,不必再寫 findViewById:
val itemView = ... itemView.itemImage.setImageResource(R.mipmap.ic_launcher) itemView.itemTitle.text = "My Text"
這一次的 import 稍有不同,多了一層布局名:
import kotlinx.android.synthetic.main.view_item.view.*
需要留意的是,這種寫法把視圖引用與具體布局耦合在一起,覆用時要清楚自己拿到的是哪一層 View。但只要用得克制,它仍然是一把非常順手的工具。
一個簡單的插件,就能把圍繞視圖查找的冗餘代碼從項目裡抹掉,同時由編譯器保證類型正確、不出差錯。這就是 Kotlin Android Extensions 帶來的開發體驗提升。
AsyncTask 基礎筆記:非同步任務的完整用法
Android 的非同步任務機制 AsyncTask,是處理背景運算並更新 UI 的常用工具。 為什麼需要非同步任務 1. Android 採單執行緒模型; 2. 耗時操
Android 主題與皮膚切換機制解析
Android 主題與皮膚切換機制解析 許多 App 會提供主題或皮膚切換功能,讓使用者能依喜好改變介面配色、圖示與樣式。常見的一種實作方式,是把主題資源打包成額外的 A
用 PopupWindow 打造仿微信右上角菜單
用 PopupWindow 打造仿微信右上角菜單 在行動應用中,右上角的「更多」入口往往需要一個簡潔、可快速關閉的浮動菜單。本文以 PopupWindow 為基礎,結合
Android 手勢滑動與自訂控制項:打造可切換頁面的互動體驗
手勢切換頁面的基本思路在 Android 應用中,除了點擊按鈕切換頁面,也可以透過滑動手勢完成同樣的操作。常見做法是在 Activity 中覆寫 onTouchEvent