当前位置: 首页 > news >正文

Android 优雅封装Glide

文章目录

  • Android 优雅封装Glide
    • 核心思想
    • 定义策略接口
    • 定义图片选项
    • 实现Glide策略
    • 图片管理类
    • 使用

Android 优雅封装Glide

核心思想

使用策略模式实现不同图片加载框架的切换,使用建造者设计模式处理不同参数,最后通过 ImageLoader 进行管理。

定义策略接口

interface ILoaderStrategy {fun loadImage(configs: ImageOptions)fun clearDiskCache(context: Context)fun clearMemoryCache(context: Context)fun clearAll(context: Context) {clearDiskCache(context)clearMemoryCache(context)}fun clear(imageView: ImageView)
}

定义图片选项

class ImageOptions private constructor() {var targetObj: Any? = null // 生命周期对象var targetView: ImageView? = null // 目标ImageViewvar resource: Any? = null // 加载资源var width = -1 // 指定宽度var height = -1 // 指定高度var isDiskCache = true // 磁盘缓存var isMemoryCache = true // 内存缓存@DrawableResvar placeholder: Int = -1 // 占位图资源@DrawableResvar error: Int = -1 // 失败图资源var listener: Listener? = nullcompanion object {fun create(): ImageOptions {return ImageOptions()}}fun with(targetObj: Any): ImageOptions {this.targetObj = targetObjreturn this}fun loadResource(resource: Any): ImageOptions {this.resource = resourcereturn this}fun size(size: Int): ImageOptions {return size(width, height)}fun size(width: Int, height: Int): ImageOptions {this.width = widththis.height = heightreturn this}fun placeholder(@DrawableRes placeholder: Int): ImageOptions {this.placeholder = placeholderreturn this}fun error(@DrawableRes error: Int): ImageOptions {this.error = errorreturn this}fun setDiskCache(isCache: Boolean): ImageOptions {isDiskCache = isCachereturn this}fun setMemoryCache(isCache: Boolean): ImageOptions {isMemoryCache = isCachereturn this}fun setListener(listener: Listener): ImageOptions {this.listener = listenerreturn this}fun into(imageView: ImageView) {this.targetView = imageViewImageLoader.loadOptions(this)}interface Listener {fun onSuccess(model: Any?)fun onFail(model: Any?)}
}

实现Glide策略

class GlideLoader : ILoaderStrategy {private lateinit var requestManager: RequestManageroverride fun loadImage(options: ImageOptions) {requestManager = getRequestManager(options.targetObj)var requestBuilder: RequestBuilder<Drawable>? = nulloptions.resource?.let {requestBuilder = generateRequestBuilder(it)}requestBuilder?.let {if (options.placeholder != -1) {it.placeholder(options.placeholder)}if (options.error != -1) {it.error(options.error)}if (options.width != -1 || options.height != -1) {it.override(options.width, options.height)}it.skipMemoryCache(options.isMemoryCache)it.diskCacheStrategy(if (options.isDiskCache) DiskCacheStrategy.AUTOMATIC else DiskCacheStrategy.NONE)options.listener?.let { listener ->it.addListener(object : RequestListener<Drawable> {override fun onLoadFailed(e: GlideException?,model: Any?,target: Target<Drawable>?,isFirstResource: Boolean): Boolean {listener.onFail(model)return false}override fun onResourceReady(resource: Drawable?,model: Any?,target: Target<Drawable>?,dataSource: DataSource?,isFirstResource: Boolean): Boolean {listener.onSuccess(model)return false}})}if (options.targetView == null) {throw IllegalArgumentException("targetView cannot be null");}it.into(options.targetView!!)}}private fun getRequestManager(targetObj: Any?): RequestManager {return if (targetObj is FragmentActivity) {Glide.with(targetObj)} else if (targetObj is Context) {Glide.with(targetObj)} else if (targetObj is View) {Glide.with(targetObj)} else if (targetObj is Fragment) {Glide.with(targetObj)} else {throw IllegalArgumentException("You cannot start a load on a null Context");}}private fun generateRequestBuilder(res: Any): RequestBuilder<Drawable>? {return if (res is String) {requestManager.load(res)} else if (res is File) {requestManager.load(res)} else {return null}}override fun clearDiskCache(context: Context) {thread {Glide.get(context).clearDiskCache()}}override fun clearMemoryCache(context: Context) {Glide.get(context).clearMemory()}override fun clear(imageView: ImageView) {Glide.with(imageView.context).clear(imageView)}
}

图片管理类

object ImageLoader {private var imageLoader: ILoaderStrategy? = nullfun setImageLoader(imageLoader: ILoaderStrategy) {this.imageLoader = imageLoader}fun with(targetObj: Any): ImageOptions {val options = ImageOptions.create()options.with(targetObj)return options}fun loadOptions(options: ImageOptions) {imageLoader!!.loadImage(options)}fun clearDiskCache(context: Context){imageLoader!!.clearDiskCache(context)}fun clearMemoryCache(context: Context){imageLoader!!.clearMemoryCache(context)}fun clearAll(context:Context){imageLoader!!.clearAll(context)}fun clear(imageView: ImageView){imageLoader!!.clear(imageView)}}

使用

override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_image_loader)imageView0 = findViewById(R.id.imageView0)imageView1 = findViewById(R.id.imageView1)imageView2 = findViewById(R.id.imageView2)ImageLoader.setImageLoader(GlideLoader())val url = "https://i-blog.csdnimg.cn/blog_migrate/de6e3262387d57977e53af596a87f582.png"ImageLoader.with(this).loadResource(url).size(100).placeholder(R.mipmap.ic_launcher).error(R.mipmap.ic_launcher).into(imageView1)ImageLoader.with(this).loadResource(File(cacheDir, "aaa.png")).placeholder(R.mipmap.ic_launcher).error(R.mipmap.ic_launcher).into(imageView2)
} 
ImageLoader.clear(imageView1)
ImageLoader.clearAll(this)
ImageLoader.clearMemoryCache(this)
ImageLoader.clearDiskCache(this)

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • Iceberg与SparkSQL整合DDL操作
  • el-table使用type=“expand”根据数据条件隐藏展开按钮
  • Ceph集群维护相关操作
  • 图特征工程实践指南:从节点中心性到全局拓扑的多尺度特征提取
  • 《系统架构设计师教程(第2版)》第17章-通信系统架构设计理论与实践-02-广域网网络架构
  • 解决MongoDB创建用户报错command createUser requires authentication
  • 设计模式-行为型模式-迭代器模式
  • 【秋招笔试】9.07美团秋招改编题(研发岗)
  • 【2024高教社杯国赛A题】数学建模国赛建模过程+完整代码论文全解全析
  • 纳米材料咋设计?蛋白质模块咋用?看这里就知道啦!
  • 数学建模_缺失值处理_拉格朗日、牛顿插值(全)
  • Android流式接口请求实践
  • 设计模式学习-责任链模式
  • JVM系列(十) -垃圾收集器介绍
  • 【阿里云】个人认证与公司认证
  • Angular4 模板式表单用法以及验证
  • github从入门到放弃(1)
  • GitUp, 你不可错过的秀外慧中的git工具
  • go语言学习初探(一)
  • java 多线程基础, 我觉得还是有必要看看的
  • JS学习笔记——闭包
  • Linux链接文件
  • PHP的类修饰符与访问修饰符
  • vue-router 实现分析
  • 闭包--闭包之tab栏切换(四)
  • 大主子表关联的性能优化方法
  • 浮动相关
  • 后端_ThinkPHP5
  • 技术攻略】php设计模式(一):简介及创建型模式
  • 可能是历史上最全的CC0版权可以免费商用的图片网站
  • 买一台 iPhone X,还是创建一家未来的独角兽?
  • 前端临床手札——文件上传
  • 前端设计模式
  • 收藏好这篇,别再只说“数据劫持”了
  • 用Canvas画一棵二叉树
  • 正则表达式
  • 正则与JS中的正则
  • 自制字幕遮挡器
  • 7行Python代码的人脸识别
  • Java总结 - String - 这篇请使劲喷我
  • 正则表达式-基础知识Review
  • # 执行时间 统计mysql_一文说尽 MySQL 优化原理
  • ###51单片机学习(2)-----如何通过C语言运用延时函数设计LED流水灯
  • #NOIP 2014#Day.2 T3 解方程
  • #宝哥教你#查看jquery绑定的事件函数
  • (152)时序收敛--->(02)时序收敛二
  • (done) NLP “bag-of-words“ 方法 (带有二元分类和多元分类两个例子)词袋模型、BoW
  • (PySpark)RDD实验实战——取最大数出现的次数
  • (附源码)ssm高校志愿者服务系统 毕业设计 011648
  • (附源码)计算机毕业设计SSM疫情下的学生出入管理系统
  • (生成器)yield与(迭代器)generator
  • (一)WLAN定义和基本架构转
  • (转)使用VMware vSphere标准交换机设置网络连接
  • .ai域名是什么后缀?
  • .Net Core/.Net6/.Net8 ,启动配置/Program.cs 配置