使用 Dagger 2 将上下文或 Activity 传递给适配器

Pass Context or Activity to adapter using Dagger 2

我在没有上下文的情况下使用 Dagger 2 注入了一个适配器,它可以正常工作,但是当我传递上下文参数时我无法执行此操作。错误是这样的

error: android.content.Context cannot be provided without an @Provides-annotated method.

匕首组件

@PerActivity
@Component(dependencies = ApplicationComponent.class, modules = MainFragmentModule.class)
public interface MainFragmentComponent {

    void inject(MainFragment mainFragment);

    @ActivityContext
    Context provideContext();
}

片段模块

@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 为你的适配器注入另一种类型的上下文 - 一种未用 @ActivityContext 注释的上下文。

相反,您应该明确定义,您愿意提供那种类型的上下文:


    @Inject
    public ConversationAdapter(..., @ActivityContext Context context) {
        ...
    }