我在没有上下文的情况下使用 Dagger 2 注入(inject)了一个适配器,它正在工作,但是当我传递上下文参数时我无法执行此操作。错误是这样来的
error: android.content.Context cannot be provided without an @Provides-annotated method.
Dagger 组件
@PerActivity
@Component(dependencies = ApplicationComponent.class, modules = MainFragmentModule.class)
public interface MainFragmentComponent {
void inject(MainFragment mainFragment);
@ActivityContext
Context provideContext();
}
fragment 模块
@Module
public class MainFragmentModule {
private MainFragmentContract.View mView;
private Activity mActivity;
Context mContext;
MainFragmentModule(MainFragmentContract.View view, Context context) {
mView = view;
mContext = context;
}
@Provides
MainFragmentContract.View providesView() {
return mView;
}
@Provides
@ActivityContext
Context provideContext() {
return mContext;
}
}
适配器
@Inject
public ConversationAdapter(MainFragmentPresenter mainPresenter, Context context) {
mMainFragmentPresenter = mainPresenter;
mContext =context;
}
最佳答案
你已经告诉 dagger,你正在提供一个特定的上下文:
@ActivityContext
Context provideContext();
然后您要求 dagger 将另一种类型的上下文注入(inject)您的适配器 - 一种未使用 @ActivityContext
注释的上下文。
相反,您应该明确定义,您愿意提供正是这种类型的上下文:
@Inject
public ConversationAdapter(..., @ActivityContext Context context) {
...
}
关于android - 使用 Dagger 2 将上下文或 Activity 传递给适配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45479621/