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

Android RoboGuice 使用指南(14):Inject View

編輯:Android 開發教學

在 Hello World 那篇中介紹了使用 RoboGuice 開發的基本步驟:

建立一個 GuiceApplication(GuiceApplication 為 Application 的子類),修改 AndroidManifest.xml 讓 Application 的 name 指向它;把原本由 Activity 派生的類別改為繼承 RoboActivity;若有需要,在 AbstractAndroidModule 中覆寫 configuration 定義 bindings。

findViewById 的痛點

如果不用 RoboGuice,當 Activity 需要存取定義在 Layout 中的某個 View 時,一般得用 findViewById 查找,再強制轉型成對應的類別。若需要存取的 View 數量多,這種重複程式碼会相當繁瑣——而且每個轉型都沒有編譯期檢查,ID 打錯或型別寫錯要到執行期才會爆。

@InjectView 的基本用法

使用 RoboGuice 的 Inject View,程式碼就簡潔易讀多了:

@InjectView(R.id.xxx) ViewType viewInstance;

其中 R.id.xxx 是該 View 在 Layout 中定義的 id(例如 R.id.textview1),ViewType 是它的型別(例如 TextView),viewInstance 則是變數名稱。

版面配置

我們定義一個 injectview.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/textview1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/injectview" />

    <TextView
        android:id="@+id/textview2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/injectview" />

    <TextView
        android:id="@+id/textview3"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/injectview" />

    <TextView
        android:id="@+id/textview4"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/injectview" />

    <Button android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:text="@string/clickmebutton"/>

</LinearLayout>

注入的時機很重要

這裡有個必須理解的前提:@InjectView 的注入發生在 super.onCreate() 之中。也就是說,你在自己的 onCreate 裡呼叫 setContentView 之後、後續程式碼執行之前,框架已經完成所有注入。

這帶來兩個實務後果:

第一,你不能在 onCreate 中 setContentView 之前使用這些變數,它們此時還是 null。

第二,如果在 Fragment 或自訂 View 中使用 @InjectView,那個「setContentView」的時機就變成 inflate 的時機,需要額外處理。

那現代專案該怎麼辦

以今天的標準來看,RoboGuice 這類框架已經不是主流選擇。Kotlin Android Extensions(已棄用)、ViewBinding 與 findViewById 搭配 Kotlin 的型別推斷,都能解決同樣的問題而不引入額外的框架依賴。

特別是 ViewBinding,它在編譯期就產生型別安全的參照,ID 寫錯直接編譯失敗,而且完全沒有執行期效能成本。如果你的專案還在用 findViewById 加一堆強制轉型,遷移到 ViewBinding 通常是很划算的投資。

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