【发布时间】:2020-10-02 18:55:53
【问题描述】:
我是 dagger 的新手,我决定使用我的众多适配器之一作为学习 dagger 2 的训练,这个适配器在其构造函数中接受了一些对象,我用 @Inject 进行了注释
@Inject
public CardAdapter(
ItemTouchListener onItemTouchListener,
@Named(layoutIdentifierName) String layoutIdentifier,
TypeFactory typeFactory
RequestManager glide,
) {
this.onItemTouchListener = onItemTouchListener;
this.layoutIdentifier = layoutIdentifier;
this.typeFactory = typeFactory;
this.elements = new ArrayList<>();
this.glide = glide;
}
Glide 是我遇到的问题,我会最后解决。
首先是 OnItemTouchListener,它是在我的片段中实现的接口,我为此创建了一个模块。它是一个抽象类,带有一个用 @Binds 注释并包含在我的组件(适配器)模块中的抽象方法
组件
@Component(modules = ItemTouchListenerModule.class)
模块
@Module
public abstract class ItemTouchListenerModule {
@Binds
abstract ItemTouchListener provideCardHolderFragmentItemTouchListener(CardHolderFragment cardHolderFragment);
}
接下来是 layoutIdentifier,它只是一个字符串,但它在运行时会发生变化,所以我让我的组件有自己的构建器并给它一个方法,这样我就可以在运行时设置它,
@BindsInstance
Builder layoutIdentifier(@Named(layoutIdentifierName) String layoutIdentifier);
接下来是TypeFactory,这是一个接口,这是另一个带有@Binds注解的模块
@Module
public abstract class TypeFactoryModule {
@Binds
abstract TypeFactory bindTypeFactory(TypeFactoryForList typeFactoryForList);
}
最后,(我遇到问题的那个)是滑翔,我实际上正在寻找提供 RequestManager,我为它创建了一个这样的模块
@Module
public class GlideModule {
public static final String glideContextName = "glide context";
private Context context;
public GlideModule(@Named(glideContextName) Context context) {
this.context = context;
}
@Provides
RequestManager provideGlide(){
return Glide.with(context);
}
}
但是如果我将它包含在我的组件模块中并在自定义构建器中添加一个方法并构建它,它会给我一个错误
error: @Component.Builder is missing setters for required modules or components: [com.sealstudios.simpleaac.dagger.GlideModule]
interface Builder {
这是我的组件,有什么想法吗?还有一个解释会很好我不认为我得到了这里发生的一切,非常感谢
@Component(modules = {TypeFactoryModule.class, ItemTouchListenerModule.class,
GlideModule.class})
public interface CardAdapterComponent {
String layoutIdentifierName = "layout identifier";
CardAdapter getCardAdapter();
void inject(CardHolderFragment cardHolderFragment);
@Component.Builder
interface Builder {
@BindsInstance
Builder layoutIdentifier(@Named(layoutIdentifierName) String layoutIdentifier);
@BindsInstance
Builder itemTouchListenerModule(CardHolderFragment cardHolderFragment);
@BindsInstance
Builder glideModule(Context context);
CardAdapterComponent build();
}
}
【问题讨论】:
标签: android adapter dagger-2 android-glide