本例實現的功能和例子Android RoboGuice 使用指南(2):第一個例子Hello World一樣,所不同的是本例使用RoboGuice2.0 來實現。
下載新的RoboGuice庫,Roboguice2.0 庫有四個庫組成,如下圖所示:
庫可以從 http://code.google.com/p/roboguice/下載。
2. 建立一個新Android項目,比如GuiceDemo,目標平台Android1.5以上。
3. 一般可以在該項目下添加一個libs目錄,將兩個jar檔案拷到libs目 錄下,然後通過: Project > Properties > Java Build Path > Libraries > Add JARs
註:從ADT17開始,添加的jar檔案需放在libs 子目錄下,可以參見升級到 ADT 17 出現dalvikvm: Unable to resolve superclass的問題
添加了對應guice 和roboguice庫的引用之後,就可以開始編寫第一個使用 roboguice2 的例子。
使用roboguice2 的步驟:
Roboguice2 中 不在含有RoboApplication 類,因此無需也不可能派生RoboApplication的子類 。這裡重複一下HelloWorld 的Layout 和類說明
1. 在這個簡單的例子中 ,它使用的Layout 定義如下:
<?xml version=”1.0″ encoding=” utf-8″?>
< LinearLayout xmlns:android=” http://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>
我們定義了一個TextView ,它的id為hello.
假定 這個應用使用一個IGreetingService ,它有一個方法getGreeting() 返回一個字 符串,至於IGreetingService 如何?,GuideDemo 不需要關心。
Dependency injection 設計模式的一個 核心原則為: Separate behavior from dependency resolution. 也就說將應用 需要實現的功能和其所依賴的服務或其它對象分離。 對本例來說GuiceDemo只要 知道它依賴於IGreetingService 服務,至於IGreetingService有誰實現 GuiceDemo並不需要知道。
在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派生(RoboActivity 為Activity的子類).
使用@Inject標註greetingServce依賴於 IGreetingService服務
使用@InjectView表示helloLabel 依賴於R.id.hello (XML)
代碼中沒有建立greetingServce 對象的代碼(如 new xxx()) 和為helloLabel 賦值的代碼。這些值都可以Roboguice 自動建立和賦值注入 (Inject)到變數中。
為了說明問題,我們在代碼中添加兩個對 getGreetings的實現,一個為HelloWorld, 一個為HelloChina:
public class HelloChina implements IGreetingService{ @Override public String getGreetings() { return "Hello,China"; } } public class HelloWorld implements IGreetingService{ @Override public String getGreetings() { return "Hello,World"; }}