2016-04-25 60 views
1

所以我正在學習匕首2,有一件事我不太關注。 所以據我所知,在組件需要specifiy可用於注入活動:匕首注射不同的活動

Singleton 
@Component(modules={AppModule.class, NetModule.class}) 
public interface NetComponent { 
    void inject(MainActivity activity); 
} 

首先爲什麼我需要指定這個的? (我從來沒有使用變量活動)。

但主要問題是讓我說我​​有10個不同的活動或片段,我需要在這裏列出它們嗎?這是做這件事的正確方式,或者我們可以注入應用程序嗎?如果我想在整個應用程序中使用NetComponent,那麼要做什麼是正確的事情。

謝謝

回答

1

如果你有一個供應組件爲你的每一個活動,所以是的。你必須爲每一個寫inject()方法。

還要注意,不能使用注射在基類,因爲它會產生這樣的錯誤:https://github.com/google/dagger/issues/214

好:

@Singleton 
@Component(modules={AppModule.class, NetModule.class}) 
public interface NetComponent { 
    void inject(MainActivity activity); 
    void inject(SplashActivity activity); 
    void inject(AnotherActivity activity); 
} 

壞:

@Singleton 
@Component(modules={AppModule.class, NetModule.class}) 
public interface NetComponent { 
    void inject(BaseActivity activity); 
} 

此外,如果你不想注射,但只能得到你的API服務等,你不能注射,但使用:

@Singleton 
@Component(modules={AppModule.class, NetModule.class}) 
public interface NetComponent { 
    SomeNetworkOrApiClass getNetworking(); 
} 

只需在您需要的時候從您的組件獲取網絡。

嘗試讀取這個有用的文章:

https://github.com/codepath/android_guides/wiki/Dependency-Injection-with-Dagger-2

https://github.com/konmik/konmik.github.io/wiki/Snorkeling-with-Dagger-2