「Glide」源码解析系列
承前启后

上一节中已经有了RequestBuilder,通过into方法将请求绑定到target上并返回
Glide.with(imageView).load("https://www.baidu.com/img/bd_logo1.png").into(imageView);
在实际使用中可能很少对target有关注,这一节就来看看它的作用
此节涉及到的类有
ImageViewTargetFactory
ViewTarget
ImageViewTarget
DrawableImageViewTarget
into

RequestBuilder共有5个into方法,除去一个过时方法不讨论,依次看一下其内部逻辑
into(@NonNull ImageView view)

此方法是外部调用频率最高的方法,经过线程判断、空判断后,进入重载方法,返回一个ViewTarget
into(@NonNull Y target,@Nullable RequestListener<TranscodeType> targetListener,@NonNull RequestOptions options)

逻辑比较清晰,创建了request,绑定到target上,并返回Target的子类
into(@NonNull Y target)
into(@NonNull Y target,@Nullable RequestListener<TranscodeType> targetListener)
这两个重载方法设置了默认参数后,最终调用了into(@NonNull Y target,@Nullable RequestListener<TranscodeType> targetListener,@NonNull RequestOptions options)方法,就不贴了!
Target的产生
绕来绕去into方法就是将新建的request与传入的target绑定,再返回出去。
找到最初进入的target,看其是哪里生成的

【通过glideContext.buildImageViewTarget方法生成的,而glideContext是经由RequestManagerRetriever->RequestManager->RequestBuilder传递过来的Glide单例获取的】


GlideContext中的ImageViewTargetFactory是在Glide单例初始化时赋值的
Target

ImageViewTargetFactory工厂类的代码并不多,但让人陷入逻辑漩涡的是泛型

还记得传入的类型吗?



是Drawable,因此工厂产生的对象为DrawableImageViewTarget
顺藤摸瓜看一下继承关系

Target

Target是一个功能接口,用来显示图片、响应生命周期变化
泛型R是请求资源图片的类型
BaseTarget

BaseTarget是设计模式中接口适配器模式产生的类,所以标了Deprecated,要自定义的话用CustomViewTarget,它的泛型Z同Target也是资源图片的类型
ViewTarget

ViewTarget的功能是将得到的资源图片显示到View上,泛型Z是图片资源类型,T是View的子类,实现了部分接口方法
ImageViewTarget

继承自ViewTarget,已经明确了ViewTarget中View的类型为ImageView
实际场景中加载图片最多的也就是ImageView了

从类的继承关系也可以看出只有ImageViewTarget属于功能型类
ImageViewTarget除了实现接口外,还留了一个抽象方法

用于ImageView设置不同的图片资源

DrawableImageViewTarget

明确了View类型为ImageView和资源类型Drawable
资源类型为Drawable时,便会调用ImageView的setImageDrawable方法
资源类型为Bitmap时,见BitmapImageViewTarget类
总结
Target的功能就是确定图片类型,响应图片加载的生命周期变化。
Target的子类ViewTarget,则增加了图片在各子View中显示的功能
网友评论