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

Android RoboGuice 使用指南(2):第一個範例 Hello World

編輯:Android 開發教學

首先說明如何把 Guice 與 RoboGuice 的庫加入專案。

下載 RoboGuice 和 guice-2.0-no_aop.jar(注意是 guice-3.0 以外的版本),或依教學下載對應檔案。接著建立一個新的 Android 專案,例如 GuiceDemo,目標平台選擇 Android 1.5 以上。

一般可以在專案下新增一個 lib 目錄,把兩個 jar 檔複製進去,然後透過:Project → Properties → Java Build Path → Libraries → Add External JARs 把它們加入建置路徑。

完成 guice 與 roboguice 庫的引用後,就可以開始撰寫第一個使用 roboguice 的範例了。

使用 roboguice 的步驟:

1. 建立一個 RoboApplication 的子類 GuiceApplication。由於 GuiceApplication 是 Application 的子類,因此需要修改 AndroidManifest.xml,把 Application 的 name 指向這個類:

<application android:name="GuiceApplication"

android:icon="@drawable/icon" android:label="@string/app_name">

<activity android:name=".GuiceDemo"

android:label="@string/app_name" >

<intent-filter>

<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

</application>

2. 這個簡單範例使用的 Layout 定義如下:

<?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 無須關心,交由 RoboGuice 透過注入來提供即可。

如此一來,第一個 RoboGuice 範例便完成了——你會發現,取得依賴不再需要手動 new,一切都交給注入框架打理。

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