Dagger 2 注入 RecyclerView 失败 - 成员无法注入原始类型

Dagger 2 injection of RecyclerView fails - cannot members inject raw type

我有一个从 RecyclerView.Adapter 扩展而来的列表适配器。我正在尝试使用 Dagger 2 注入它,但它因错误

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

主要文件内容如下(删除无关行)

ListAdapter.java

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

ListFragment.java

public class ListFragment extends Fragment {
    @Inject 
    ListAdapter listAdapter
}

InjectionModule.java

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

InjectionComponent.java

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

我在谷歌上进行了大量搜索,发现 this article 我认为我有效地使用了文章中途提到的超类方法,但它对我不起作用。希望有人成功地用 Dagger 2 注入了 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 应该 知道在哪里可以找到 Context 对象。您可以像这样通过构造函数在模块中传递上下文

@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);