Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

告別 findViewById:Kotlin Android Extensions 實戰(KAD 04)

編輯:關於 Android 開發

告別 findViewById:Kotlin Android Extensions 實戰(KAD 04)

作者:Antonio Leiva 時間:2016 年 12 月 12 日 原文:https://antonioleiva.com/kotlin-android-extensions/

日復一日地寫 findViewById,大概每個 Android 開發者都會感到疲憊。有些人乾脆轉投 ButterKnife 這類依賴注入庫。如果你也屬於這一群人,那麼 Kotlin 的 Android 擴展插件一定會讓你愛不釋手。

什麼是 Kotlin Android Extensions

它是 Kotlin 官方插件家族中的一員,能無縫地把 Activity、Fragment 以及自定義 View 中的視圖引用直接暴露出來,讓 XML 裡的 id 變成可以直接調用的屬性。

在項目中啟用它

使用插件並不需要額外寫依賴,只要在 Android 模塊的 build.gradle 中追加一行 apply:

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

添加完這幾行,一切就準備就緒了。

在 Activity 或 Fragment 中訪問視圖

啟用插件之後,訪問視圖變得跟在 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 帶來的開發體驗提升。

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