Android 中关于 Glide 的 SimpleTarget ViewTarget 和 CustomTarget CustomViewTarget 方法的理解

Glide4将SimpleTarget(自由使用Target)和ViewTarget(自定义View中使用Target)废弃了,分别由CustomTarget和CustomViewTarget代替,原因:

  • 使用SimpleTarget不会强制要求实现onLoadCleared方法,容易造成显示错乱或者奔溃问题;
  • 使用ViewTarget也不强制要求实现onLoadCleared方法,也容易出问题;即使实现了也要求必须要在onLoadCleared中调用super.onLoadCleared方法(使用者都容易忽略),否则还是会出问题;
  • 使用CustomTarget则要求必须实现onLoadCleared方法;
  • 使用CustomViewTarget则不需要实现onLoadCleared(final的),而是要求必须实现onResourceCleared方法(在onLoadCleared方法中调用)。

总的来说就是保证资源能够得到正常释放!

CustomTarget使用示例:

Glide.with(this)
        .asBitmap()
        .load(imagePath)
        .into(object : CustomTarget<Bitmap>(){
            override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                imageView.setImageBitmap(resource)
            }
            override fun onLoadCleared(placeholder: Drawable?) {
                // this is called when imageView is cleared on lifecycle call or for
                // some other reason.
                // if you are referencing the bitmap somewhere else too other than this imageView
                // clear it here as you can no longer have the bitmap
            }
        })
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容