私は Android Databinding アダプターを使用していますが、それは静的でなければならないと言っています。だから私はそれを非静的にし、このチュートリアルに従って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);
}
}
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;
}
}