我正在使用Android Databinding适配器,它说它必须是静态的。因此,我尝试使它成为非静态的,并按照this tutorial使用Dagger将我的类注入其中。尽管我可以使用dagger通常在应用程序中提供的Picasso
实例,但它显示为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
问题有关,因此改变了我的方法,并遵循this link并使用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);
}
}
BindingModule类
@Module
public class BindingModule {
@Provides
@DataBinding
ImageBindingAdapter provideImageBindingAdapter(Picasso picasso) {
return new ImageBindingAdapter(picasso);
}
}
BindingComponent类
@DataBinding
@Component(dependencies = AppComponent.class, modules = BindingModule.class)
public interface BindingComponent extends DataBindingComponent {
}
AppComponent类
@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);
}
AppModule类
@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;
}
}
答案 0 :(得分:0)
正如错误所述,匕首无法解决Picasso
依赖性。在您的情况下,问题在于区别匕首组件只能直接使用那些依赖项,即使用方法声明的带有@Component
批注的接口。要允许AppComponent
与Picasso
共享BindingComponent
,您需要像这样修改应用程序组件:
@Singleton
@Component(modules = {AndroidSupportInjectionModule.class, AppModule.class, ...})
public interface AppComponent extends AndroidInjector<MyApp> {
...
Picasso getPicasso();
}
此后,匕首可以正确解决Picasso
依赖性,错误应该消失。
答案 1 :(得分:0)
@BindingAdapter应该为public static void
,请参见Binding adapters docs。