我正在使用 Android 数据绑定适配器,它说,它必须是静态的。因此,我试图使其成为非静态的,并按照本教程使用 Dagger 将我的类注入其中。虽然我可以Picasso
在应用程序中正常使用 dagger 提供的实例,但它说Picasso cannot be provided without an @Inject constructor or an @Provides-annotated method
。
我将@Inject 注释添加到我的绑定适配器构造函数,但仍然得到相同的错误
public class ImageBindingAdapter {
private final Picasso picasso;
@Inject
public ImageBindingAdapter(Picasso picasso) {
this.picasso = picasso;
}
@BindingAdapter("android:src")
public void loadImage(ImageView view, String url) {
picasso.load(url).fit().into(view);
}
}
我认为该问题可能与某个component
问题有关,并改变了我的方法并遵循此链接并使用subcomponent
. 但是这次匕首无法生成子组件,我无法像示例中那样设置它
// Build dagger binding subcomponent and set it like default databinding component
DataBindingUtil.setDefaultComponent(sApplicationComponent
.daggerBindingComponentBuilder()
.build());
如何使用 Dagger 将我的自定义类注入到绑定适配器中,不胜感激
这是我的匕首类,与我上面提到的教程非常相似
ImageBindingAdapter 类
public class ImageBindingAdapter {
private final Picasso picasso;
@Inject
public ImageBindingAdapter(Picasso picasso) {
this.picasso = picasso;
}
@BindingAdapter("android:src")
public void loadImage(ImageView view, String url) {
picasso.load(url).fit().into(view);
}
}
绑定模块类
@Module
public class BindingModule {
@Provides
@DataBinding
ImageBindingAdapter provideImageBindingAdapter(Picasso picasso) {
return new ImageBindingAdapter(picasso);
}
}
绑定组件类
@DataBinding
@Component(dependencies = AppComponent.class, modules = BindingModule.class)
public interface BindingComponent extends DataBindingComponent {
}
应用组件类
@Singleton
@Component(modules = {AndroidSupportInjectionModule.class, AppModule.class, ...})
public interface AppComponent extends AndroidInjector<MyApp> {
@Component.Builder
interface Builder {
@BindsInstance
Builder application(Application application);
AppComponent build();
}
@Override
void inject(MyApp instance);
}
应用模块类
@Module
public class AppModule {
@Singleton
@Provides
Picasso picasso(Application application, OkHttp3Downloader okHttp3Downloader) {
return new Picasso.Builder(app.getApplicationContext())
.downloader(okHttp3Downloader)
.indicatorsEnabled(true)
.build();
}
....
}
应用类
public class MyApp extends DaggerApplication {
@Override
protected AndroidInjector<MyApp> applicationInjector() {
AppComponent appComponent = DaggerAppComponent.builder().application(this).build();
appComponent.inject(this);
BindingComponent bindingComponent = DaggerBindingComponent.builder()
.appComponent(appComponent)
.build();
DataBindingUtil.setDefaultComponent(bindingComponent);
return appComponent;
}
}