編輯:Android 開發教學
本例要實現的功能與 RoboGuice 1.x 版本的 Hello World 完全相同,差別只在改用 RoboGuice2.0 來實作。透過對照,你能清楚看到兩代之間的變化。
RoboGuice 2.0 由四個 jar 檔組成:

可從 https://code.google.com/p/roboguice/ 下載。
建立一個新的 Android 專案(例如 GuiceDemo),目標平台選 Android 1.5 以上。
在專案下建立一個 libs 目錄,把 jar 檔複製進去,然後透過 Project → Properties → Java Build Path → Libraries → Add JARs 加入參照。

注意:從 ADT 17 開始,加入的 jar 檔必須放在 libs 子目錄下。
RoboGuice2 中已經不再包含 RoboApplication 類,因此無需也不可能派生它的子類。這是升級時最直觀的差異。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="@+id/hello"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
</LinearLayout>
這裡定義了一個 id 為 hello 的 TextView。
假設這個應用使用一個 IGreetingService,它有個 getGreeting() 方法回傳字串。至於 IGreetingService 由誰實作,GuiceDemo 完全不關心。

相依注入設計模式的核心原則是:Separate behavior from dependency resolution——把「應用要實現的功能」與「它依賴的服務或其他物件」分離開來。
對本例來說,GuiceDemo 只知道它依賴 IGreetingService 這個服務,至於具體實作者是誰,它不需要也不應該知道。在 RoboGuice 中,用 @Inject 來表達這種依賴關係。
public class GuiceDemo extends RoboActivity {
@InjectView(R.id.hello) TextView helloLabel;
@Inject IGreetingService greetingServce;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
helloLabel.setText(greetingServce.getGreetings());
}
}
三個關鍵點:
使用 RoboGuice 的 Activity 必須從 RoboActivity 派生(它是 Activity 的子類)。
@Inject 標註 greetingServce 依賴於 IGreetingService 服務。
@InjectView 表示 helloLabel 依賴於 XML 中的 R.id.hello。
注意程式碼中沒有建立 greetingServce 物件的程式碼(例如 new XXX()),也沒有為 helloLabel 賦值。這些都由 RoboGuice 自動建立並注入。
為了示範切換實作的容易程度,我們準備兩個實作:
public class HelloChina implements IGreetingService {
@Override
public String getGreetings() {
return "Hello,China";
}
}
public class HelloWorld implements IGreetingService {
@Override
public String getGreetings() {
return "Hello,World";
}
}
切換 HelloWorld 與 HelloChina,你完全不需要改動 GuiceDemo 的任何一行程式碼——只要調整綁定設定即可。
這正是相依注入的價值所在:把「用什麼」與「怎麼用」解耦。在沒有 DI 的情況下,一旦要換實作,你就得搜尋所有 new HelloWorld() 的地方逐一替換;有了 DI,切換只是一個設定檔的改動。
這個特性在寫單元測試時尤其可觀——把真實服務換成 Mock 實作,測試就能在不啟動網路、不連資料庫的情況下運行。
Android 選單(三):實作情境選單 ContextMenu
上一節說明了按 MENU 鍵時如何顯示選項選單。除了選項選單,Android 還有情境選單——它通常與 Activity 中的某個元件相關聯,當使用者長按該元件時觸發。例
AndroidAnnotations(AA)開源框架簡介:以編譯期注解取代反射
框架定位 AndroidAnnotations 是一個開源框架,目標是加快 Android 開發效率。透過它提供的注解 API,你可以在幾乎任何地方使用,大幅削減無關痛癢
Android 命令行截屏 screencap 使用說明
在無法使用 USB 或圖形工具的環境中,Android 可透過命令列完成截屏。Android 4.0 以後內建 screencap 命令,能將目前畫面儲存為圖片檔。基本用
Android 開發札記(5):方法調用的基礎用法
在實際的程式執行過程中,程式碼通常是由上而下、逐句執行,直到遇到「}」才告一段落。然而當相同的邏輯(例如重複的布局設定或相同功能)在不同地方一再出現時,如果每次都要複製貼