編輯:關於 Android 程式設計
Dagger 2 是由 Google 的技術團隊主導開發的依賴注入框架,Square 的成員與許多貢獻者也都投入其中。相比 Dagger 1.x,它在編譯期就能生成程式碼,效能與可讀性都有明顯提升。本文透過一個完整 Demo,帶你快速上手 Dagger 2。

在 Dagger 1.x 中,@Inject 與 @Provides 兩個註解共同構成了物件圖譜(graph),並依靠彼此間的依賴關係鏈接在一起,透過 ObjectGraph 就能方便地調用程式碼。而在 Dagger 2 中,這種關係改由帶有無參數方法的介面取代,方法回傳的型別即為所需型別。這種介面透過 @Component 註解並傳入 modules 參數來定義:
@Component(
// dependencies = ApplicationComponent.class,
modules = ActivityModule.class
)
public interface ActivityComponent {
MainActivity injectActivity(MainActivity activity);
ToastHelper getToastHelper();
}
編譯時,Dagger 2 會自動生成以 Dagger_ 為前綴的介面實作,例如 Dagger_ActivityComponent。透過它的 builder() 方法取得實例,再設定其他依賴,最後用 build() 得到新實例:
this.component = Dagger_ActivityComponent.builder()
// .applicationComponent(((DaggerApplication) getApplication()).getComponent())
.activityModule(new ActivityModule(this))
.build();
另外,若 @Component 介面中的方法沒有參數,生成的實例還會多出一個 create() 方法,它其實就等同於 builder().build()。
Demo 採用 Android Studio 1.0.2,gradle.build 設定如下:
apply plugin: 'com.android.application'
apply plugin: 'android-apt'
buildscript {
repositories { jcenter() }
dependencies {
classpath 'com.android.tools.build:gradle:1.0.0'
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.4'
}
}
allprojects {
repositories {
mavenCentral()
maven { url 'https://oss.sonatype.org/content/repositories/snapshots/' }
}
}
def Dagger2_Version = '2.0-SNAPSHOT'
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:21.0.3'
compile "com.google.dagger:dagger:$Dagger2_Version"
apt "com.google.dagger:dagger-compiler:$Dagger2_Version"
compile 'org.glassfish:javax.annotation:10.0-b28'
}
這裡有幾個關鍵點:Dagger 2 的座標已從 com.square.dagger 改為 com.google.dagger;之所以要額外加入 javax.annotation,是因為 Dagger 2 會用到 @Generated 註解,而 Android API 本身並沒有提供它;此外也別忘了加上 apply plugin: 'android-apt'。
@Module 依然是核心註解。Demo 中用到兩個 Module:
@Module
public class ActivityModule {
private Activity mActivity;
public ActivityModule(Activity activity) { mActivity = activity; }
@Provides Activity providesActivity() { return mActivity; }
}
@Module
public class ApplicationModule {
Application mApplication;
ApplicationModule(Application application) { mApplication = application; }
@Provides Application providesApplication() { return mApplication; }
}
@Component(
dependencies = ApplicationComponent.class,
modules = ActivityModule.class
)
public interface ActivityComponent {
MainActivity injectActivity(MainActivity activity);
ToastHelper getToastHelper();
}
@Component(modules = ApplicationModule.class)
public interface ApplicationComponent {
DaggerApplication injectApplication(DaggerApplication application);
}
public class DaggerApplication extends Application {
private ApplicationComponent component;
@Override public void onCreate() {
super.onCreate();
this.component = Dagger_ApplicationComponent.builder()
.applicationModule(new ApplicationModule(this)).build();
this.component.injectApplication(this);
}
ApplicationComponent getComponent() { return this.component; }
}
public class ToastHelper {
@Inject ToastHelper() { }
Toast toast = null;
public void showToast(Context context, CharSequence text) {
if (toast == null) {
toast = Toast.makeText(context, text, Toast.LENGTH_LONG);
} else {
toast.setText(text);
}
toast.show();
}
}
public class MainActivity extends Activity {
private ActivityComponent component;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.component = Dagger_ActivityComponent.builder()
.applicationComponent(((DaggerApplication) getApplication()).getComponent())
.activityModule(new ActivityModule(this))
.build();
this.component.injectActivity(this);
setContentView(R.layout.activity_main);
}
public void helloDagger2(View v) {
this.component.getToastHelper().showToast(this, "Dagger 2 Demo");
}
}
Dagger 2 移除了 1.x 中所有依賴反射的映射,透過 @Component 取代 ObjectGraph/Injector,讓程式碼更加清晰。值得一提的是,Dagger 2 更鼓勵用 @Component 介面把依賴關係串接起來,而非單純靠 @Inject 直接注入——兩者雖能達到相同效果,但 Dagger 自動生成的程式碼會有所差異,這部分值得日後深入探討。
手把手實現 Android 下拉刷新:自定義 RefreshableView 全解析
下拉刷新幾乎是列表頁的事標。本文用「組合 View」的思路自己造一個:自定義一個繼承 LinearLayout 的容器,裡面縱向放「下拉頭」和 ListView 兩個子元
用 PagerSlidingTabStrip 打造帶標籤的多頁面滑動切換
這裡我們會用到兩個庫:一個是 Android SDK 自帶的 android-support-v4,另一個是開源的 PagerSlidingTabStrip,專案地址為
自定義屬性實作帶邊框線的 TextView 控制項
當系統自帶屬性無法滿足需求時,就得替控制項加上自定義屬性。這裡示範一個很典型的例子:讓文字方塊能單獨顯示左、上、右、下任一邊的邊框線。不用自定義屬性當然也做得到,但把「要
Android 有道詞典的簡易實作教學
本文將動手打造一個迷你版的「有道詞典」:使用者在輸入框輸入單字,點擊查詢後,透過 WebView 載入有道詞典的線上查詢結果頁面即可顯示翻譯。這是一個結合 EditTex