回收器视图的匕首 2 注入失败 - 成员无法注入原始类型



>我有一个从RecyclerView.Adapter扩展的列表适配器。 我正在尝试使用dagger 2 注入它,但它失败并出现错误

Error:android.support.v7.widget.RecyclerView.Adapter has type parameters, cannot members inject the raw type. via:
ListAdapter

突出文件内容如下(删除不相关行(

列表适配器.java

public class ListAdapter extends RecyclerView.Adapter {
  public ListAdapter(Context context) {
  }

列表片段.java

public class ListFragment extends Fragment {
    @Inject 
    ListAdapter listAdapter
}

注射模块.java

@Module
public class InjectionModule {
    @Provides
    ListAdapter provideLisAdapter(Context context) {
        return new ListAdapter(context);
    }
}

注塑组件.java

@Component (modules = InjectionModule.class)
public interface InjectionComponent {
    void inject(ListFragment listFragment);
}

用谷歌搜索了大量内容并找到了这篇文章,我认为我有效地使用了文章中途提到的超类方法,但它对我不起作用。 希望有人设法用dagger2注入RecyclerView.Adapter,如果是这样,可以分享解决方案。

替换

@Component (modules = InjectionModule.class)
  public interface InjectionComponent {
  void inject(ListAdapter listAdapter);
}

@Component (modules = InjectionModule.class)
  public interface InjectionComponent {
  void inject(ListFragment listFragment);
}

此外,为了在模块中构造ListAdapter对象,dagger应该知道在哪里可以找到上下文对象。你可以像这样通过构造函数在模块中传递上下文

@Module
public class InjectionModule {
Context context;
  public InjectionModule(Context context) {
      this.context = context;
   }
  @Provides
  ListAdapter provideLisAdapter() {
      return new ListAdapter(context);
  }
}

然后在您的 ListFragment 中注入您的依赖项,如下所示:

DaggerInjectionComponent.builder()
   .injectionModule(new InjectionModule(getActivity())
   .build()
   .inject(this);

最新更新