1

我使用Dagger 2注入了一个无上下文的适配器,它正在工作,但是当我传递上下文参数时,我无法做到这一点。错误来了这样使用匕首将上下文或活动传递给适配器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; 
    } 
+0

您可以添加(?活动)的代码,在使用的适配器?在这个类中包含Dagger初始化。 – Christopher

+0

我无法添加片段代码...当我点击保存时发生错误。 – Jarvis

+0

DaggerMainFragmentComponent.builder()。applicationComponent(((QTConnectApp)getActivity()。getApplication())。getComponent()) .mainFragmentModule(new MainFragmentModule(this,getContext())) .build().injection(this) ; – Jarvis

回答

4

你告诉匕首,你所提供的是特定的上下文:

@ActivityContext 
Context provideContext(); 

然后,您要求匕首将您的适配器注入另一种类型的上下文 - 其中一个不带注释的@ActivityContext

相反,你应该明确定义,你是愿意提供正是类型的上下文:

 

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

谢谢..其完成,请帮助我,如果想传递活动而不是上下文。 – Jarvis

相关问题