編輯:Android 開發教學
在 Hello World 那篇中介紹了使用 RoboGuice 開發的基本步驟:
建立一個 GuiceApplication(GuiceApplication 為 Application 的子類),修改 AndroidManifest.xml 讓 Application 的 name 指向它;把原本由 Activity 派生的類別改為繼承 RoboActivity;若有需要,在 AbstractAndroidModule 中覆寫 configuration 定義 bindings。
如果不用 RoboGuice,當 Activity 需要存取定義在 Layout 中的某個 View 時,一般得用 findViewById 查找,再強制轉型成對應的類別。若需要存取的 View 數量多,這種重複程式碼会相當繁瑣——而且每個轉型都沒有編譯期檢查,ID 打錯或型別寫錯要到執行期才會爆。
使用 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 通常是很划算的投資。
Android 子線程更新 UI 的完整方式與原理釐清
一、為何寫這篇 你是不是常在書上看到「不能在子線程中操作 UI,否則會報錯」這句話?但實際動手時,卻可能遇到矛盾的情況。看看下面這段程式碼: @Override pro
Activity 層級的按鍵處理:覆寫 onKeyDown()
使用者可以在兩個層級與你的 UI 互動:Activity 層級與 View 層級。在 Activity 層級,Activity 類別暴露了一些可供覆寫的方法,常用的有:
Android中如何實現Socket大文件斷點上傳
Socket 是網路通信中常見的端點抽象。Android 可透過 Socket 實作大檔案上傳,並結合伺服器回傳的續傳位置,達到斷點上傳的效果。核心概念TCP 是面向連線
Android 手機平板兩用:使用 Fragment 實作相容介面
同一套應用程式若要同時支援手機與平板,可透過 Fragment 將畫面模組化。手機版可將不同 Fragment 放在不同 Activity,平板版則可在同一畫面並排顯示。