我使用匕首2.11并且无法注入视图out of the box,但我设法这样做了:
BindingModule:
@Module(subcomponents = {...})
public abstract class ViewBindingModule {
@Binds
@IntoMap
@ViewKey(MyView.class)
abstract AndroidInjector.Factory<? extends BaseView> myView(MyViewSubComponent.Builder builder);
}
MyViewSubComponent:
@Subcomponent(modules = MyViewModule.class)
public interface MyViewSubComponent extends AndroidInjector<MyView> {
@Subcomponent.Builder
abstract class Builder extends AndroidInjector.Builder<MyView> {}
}
MyViewModule:
@Module
public abstract class MyViewModule extends ViewModule<MyView> {
public MyViewModule(MyView view) {
super(view);
}
}
ViewModule:
@Module
public abstract class ViewModule<V extends View> {
protected final V view;
public ViewModule(V view) {
this.view = view;
}
@Provides
@ViewScope
V provideView() {
return view;
}
}
BaseView:
ViewInjection.inject(this);
ViewInjection 几乎是其他Injectors的副本。
现在,我有一个Activity,一个CustomView和一个BaseViewModel。我的BaseViewModel包含一个需要AppCompatActivity实例的Object。
我将其视为休闲:
ActivityBindingModule :
@Module
public abstract class ActivityBindingModule {
@ActivityScope
@ContributesAndroidInjector(modules = MyActivityModule.class)
abstract MyActivity activity();
}
MyActivityModule
@Module
public abstract class MyActivityModule {
@Binds
abstract AppCompatActivity activity(MyActivity activity);
}
需要上下文的对象:
@Inject
public Object(AppCompatActivity activity, ...)
BaseViewModel :
public BaseViewModel(Object object,...)
ViewModel(扩展BaseViewModel):
@Inject
public ChildViewModel(Object object,...){super(object,...);...}
在Activity中注入我的BaseViewModel时,这种配置非常有效(&#34; View&#34;),但是如果我想向View(@Inject BaseViewModel inside a BaseView
)提供BaseViewModel,我将会这样做有一个问题因为我的Object需要ActivityBindingModule / MyActivityModule提供的Activity @ActivityScope
而不是@ViewScope
:
Error:(27, 1) error: [dagger.android.AndroidInjector.inject(T)] android.support.v7.app.AppCompatActivity cannot be provided without an @Inject constructor or from an @Provides-annotated method.
android.support.v7.app.AppCompatActivity is injected at
com.myapp.MyObject.<init>(activity, …)
com.myapp.MyObject is injected at
com.myapp.MyViewModel.<init>(object, …)
com.myapp.MyViewModel is injected at
com.myapp.MyViewModel.mMyViewModel
com.myapp.MyView is injected at
dagger.android.AndroidInjector.inject(arg0)
A binding with matching key exists in component: com.myapp.di...ActivityBindingModule_MyActivity.MyActivitySubcomponent
...
我不知道我是否在这里清楚,或许有点混乱,但我怎样才能做到这一点?
谢谢你的时间。