Dagger 2和Android数据绑定适配器:如果没有@Inject或@Provides

时间:2018-10-26 04:10:43

标签: android dagger-2 android-databinding

我正在使用Android的数据绑定库和Dagger2。我想在RecyclerView中显示图像时使用DatabingAdapter。我有使用Dagger创建的Picasso实例,并且必须将其注入创建的DatabindingAdapter中。我按照本教程here进行操作,但遇到一个错误,即如果没有@Inject或@Provides带注释的方法,将无法提供Picasso。这是我的代码(简化了类以使其更多地关注这个问题,我早已使毕加索工作了。)

AppModule.java

@Module(includes = {AndroidInjectionModule.class, NetworkModule.class, ViewModelModule.class})
public class AppModule {

    @Provides
    @AppScope
    Picasso picasso(App app, OkHttp3Downloader okHttp3Downloader) {
        return new Picasso.Builder(app.getApplicationContext())
                .downloader(okHttp3Downloader)
                .indicatorsEnabled(true)
                .build();
    }
}

BindingModule.java

@Module
public class BindingModule {
    @BindingScope
    @Provides
    ImageBindingAdapter provideImageBindingAdapter(Picasso picasso) {
        return new ImageBindingAdapter(picasso);
    }
}

BindingComponent.java

@BindingScope
@Component(dependencies = AppComponent.class, modules = BindingModule.class)
public interface BindingComponent extends androidx.databinding.DataBindingComponent {
}

AppComponent.java

@AppScope
@Component(modules = {AppModule.class, AndroidSupportInjectionModule.class, ActivityBuildersModule.class})
public interface AppComponent {

    void inject(App app);

    @Component.Builder
    interface Builder {
        @BindsInstance
        Builder application(App application);

        AppComponent build();
    }
}

ImageBindingAdapter.java

public class ImageBindingAdapter {

    private final Picasso picasso;

    public ImageBindingAdapter(Picasso picasso) {
        this.picasso = picasso;
    }

    @BindingAdapter(value = "url")
    public void loadImageUrl(ImageView imageView, String url) {
        if (url != null && !url.trim().isEmpty())
            picasso.load(Constants.ENDPOINT + url).into(imageView);
    }
}

这就是错误所在。

error: [Dagger/MissingBinding] com.squareup.picasso.Picasso cannot be provided without an @Inject constructor or an @Provides-annotated method.
com.squareup.picasso.Picasso is injected at
com.ralphevmanzano.themoviedb.di.modules.BindingModule.provideImageBindingAdapter(picasso)
com.ralphevmanzano.themoviedb.databinding.ImageBindingAdapter is provided at
androidx.databinding.DataBindingComponent.getImageBindingAdapter()

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

您在@Inject类中缺少ImageBindingAdapter注释

@AppScope
public class ImageBindingAdapter {

    private final Picasso picasso;

    @Inject
    public ImageBindingAdapter(Picasso picasso) {
        this.picasso = picasso;
    }

    @BindingAdapter(value = "url")
    public void loadImageUrl(ImageView imageView, String url) {
        if (url != null && !url.trim().isEmpty())
            picasso.load(Constants.ENDPOINT + url).into(imageView);
    }
}

添加@Inject告诉dagger将此类添加到图形中,然后可以将范围注释添加到您的类中,以告知该类添加到哪个范围。

ps:您可以删除自己的BindingModule