如果您在此課程中沒有任何其他依賴項,那麼您的活動可能不是依賴項,您可以使用new
。但是,爲了回答你的問題,你想爲你的活動與這樣的模塊子(或這類活動):
@Module
public class TestModule {
private final String arg1;
private final int arg2;
private final boolean arg3;
public TestModule(String arg1, int arg2, boolean arg3) {
this.arg1 = arg1;
this.arg2 = arg2;
this.arg3 = arg3;
}
@Provides DaggerTestClass provideDaggerTestClass() {
return new DaggerTestClass(arg1, arg2, arg3);
}
}
和你使用它像:
IndexApplication.getApplication().getAppComponent()
.daggerTestSubcomponent(new DaggerTestModule("arg1", 2, true))
.inject(this);
如果你在這個類有其他的依賴,雖然,那麼你可能想實際使用工廠(您使用AutoFactory對可能產生的),然後在「手動進」創建的對象:
private DaggerTestClass daggerTestClass; // note: no @Inject here
// …
// Inject other dependencies into the activity
IndexApplication.getApplication().getAppComponent().inject(this);
// "manually inject" the DaggerTestClass
this.daggerTestClass = IndexApplication.getApplication().getAppComponent()
.daggerTestFactory().create("arg1", 2, true);
謝謝,我需要廣告依賴注入,我只是舉了一個例子來描述爲什麼我不能注入我現有的類。我想這就是我想要的。 – user3057944
我試圖實現你建議的解決方案,但我沒有方法.daggerTestFactory() – user3057944
的確,你必須添加它! (或者將它注入到你的活動中,但是因爲你只會用它來初始化另一個域......) –