用匕首2注入数据绑定适配器



我使用的是Android数据绑定适配器,它说,它必须是静态的。因此,我正在努力使它成为非静态的,并通过遵循本教程将我的类用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问题有关,并改变了我的方法,按照这个链接使用了subcomponent。但这一次dagger不能生成子组件,我也不能像的例子那样设置它

// Build dagger binding subcomponent and set it like default databinding component 
DataBindingUtil.setDefaultComponent(sApplicationComponent
.daggerBindingComponentBuilder()
.build());

如何使用Dagger将我的自定义类注入绑定适配器,将不胜感激

这是我的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;
}
}

如错误所述,dagger无法解析Picasso依赖关系。在您的案例中,问题是不同的dagger组件只能直接使用那些依赖项,即用方法声明的@Component注释标记的接口。要允许AppComponentBindingComponent共享Picasso,您需要修改如下应用程序组件:

@Singleton 
@Component(modules = {AndroidSupportInjectionModule.class, AppModule.class, ...}) 
public interface AppComponent extends AndroidInjector<MyApp> { 
...
Picasso getPicasso();
}

之后dagger可以正确地解决Picasso依赖关系,错误应该会消失。

@BindingAdapter应为public static void,请参阅Binding adapters文档。

最新更新