我做了一个简单的项目来学习 Dagger。该应用程序正在从互联网获取特性列表(度假出租屋)并将其显示在 RecyclerView
上。列表。我使用 Dagger 2 注入(inject)了除列表适配器之外的所有依赖项。该适配器非常标准,它采用属性列表并填充 View :
public class PropertyListAdapter extends RecyclerView.Adapter<PropertyListAdapter.ViewHolder> {
private List<Property> mPropertyList;
@Inject
public PropertyListAdapter(List<Property> propertyList) {
mPropertyList = propertyList;
}
// onCreateViewHolder()
// onBindViewHolder()
// getItemCount()
// class ViewHolder{}
}
该应用程序由一个 Activity 组成,该 Activity 包含一个 fragment ,其中包含 recyclerview
列表。在 fragment 的onActivityCreated()
中我有:
mPropertyViewModel.getPropertyList().observe(this, properties -> setPropertyAdapter(properties));
和setPropertyAdapter()
是:
private void setPropertyAdapter(List<Property> properties) {
rvPropertyList.setAdapter(new PropertyListAdapter(properties));
}
所以,注入(inject)PropertyListAdapter
我创建了一个模块:
@Module
public class AdapterModule {
@Provides
@Singleton
PropertyListAdapter providePropertyListAdapter(List<Property> propertyList) {
return new PropertyListAdapter(propertyList);
}
}
但后来我意识到我必须注入(inject) List<Property>
我不知道如何实现这一目标,我陷入了困境。本例中如何注入(inject)适配器?
附注我将 MVVM 与架构组件一起使用。
Logcat:error: [dagger.android.AndroidInjector.inject(T)] java.util.List<com.aandritchi.android.propertyrentals.data.domain.Property> cannot be provided without an @Provides-annotated method.
java.util.List<com.aandritchi.android.propertyrentals.data.domain.Property> is injected at
com.aandritchi.android.propertyrentals.di.module.data.AdapterModule.providePropertyListAdapter(propertyList)
com.aandritchi.android.propertyrentals.ui.search_result.PropertyListAdapter is injected at
com.aandritchi.android.propertyrentals.ui.search_result.PropertySearchResultFragment.mPropertyListAdapter
com.aandritchi.android.propertyrentals.ui.search_result.PropertySearchResultFragment is injected at
com.aandritchi.android.propertyrentals.ui.home.HomeActivity.mPropertySearchResultFragment
com.aandritchi.android.propertyrentals.ui.home.HomeActivity is injected at
dagger.android.AndroidInjector.inject(arg0)
最佳答案
你应该问自己:我真的需要注入(inject)适配器吗?
您想要这样做的两个原因:
1) 适配器具有您要注入(inject)的依赖项。这不是你的情况,因为除了属性列表之外没有任何其他依赖项。
2) 您希望从 Activity/Fragment 中删除创建适配器实例的责任。
这两个问题的正确解决方案是注入(inject)一个工厂,它已经注入(inject)了所有可注入(inject)的依赖项,并提供了创建实例的方法。
关于java - 不知道如何为 RecyclerView 注入(inject)适配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50228527/