我应该在BindAdapter类中使用注入吗?

时间:2019-07-09 10:10:20

标签: android data-binding dependency-injection dagger-2

我有这种方法:

/**
 * Uses the Glide library to load an image by URL into an [ImageView]
 */
@BindingAdapter("imageUrl")
fun bindImage(imgView: ImageView, imgUrl: String?) {
    imgUrl?.let {
        val imgUri = imgUrl.toUri().buildUpon().scheme("https").build()
        Glide.with(imgView.context)
            .load(imgUri)
            .apply(
                RequestOptions()
                    .placeholder(R.drawable.loading_animation)
                    .error(R.drawable.ic_broken_image)
            )
            .into(imgView)
    }
}

在BindAdapter文件中。

我应该使用匕首在此方法中注入匕首吗?

如果是这样,由于BindAdapter是文件而不是类,我该怎么办?

1 个答案:

答案 0 :(得分:1)

 You can try this way
  @Singleton
  @Provides
  static RequestOptions provideRequestOptions(){
    return RequestOptions
            .placeholderOf(R.drawable.loading_animation)
            .error(R.drawable.ic_broken_image);
  }

  @Singleton
  @Provides
  static RequestManager provideGlideInstance(Application application, 
  RequestOptions requestOptions){
    return Glide.with(application)
            .setDefaultRequestOptions(requestOptions);
  }


  In DataBinding Class
   @Inject
   RequestManager requestManager;

   @BindingAdapter("imageUrl")
  fun bindImage(imgView: ImageView, imgUrl: String?) {
  imgUrl?.let {
    val imgUri = imgUrl.toUri().buildUpon().scheme("https").build()
    requestManager
        .load(imgUri)
        .into(imgView)
   }
}