Android 优雅封装Glide

2024-09-07 12:44
文章标签 android 封装 优雅 glide

本文主要是介绍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)

这篇关于Android 优雅封装Glide的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1145094

相关文章

Android 悬浮窗开发示例((动态权限请求 | 前台服务和通知 | 悬浮窗创建 )

《Android悬浮窗开发示例((动态权限请求|前台服务和通知|悬浮窗创建)》本文介绍了Android悬浮窗的实现效果,包括动态权限请求、前台服务和通知的使用,悬浮窗权限需要动态申请并引导... 目录一、悬浮窗 动态权限请求1、动态请求权限2、悬浮窗权限说明3、检查动态权限4、申请动态权限5、权限设置完毕后

Android里面的Service种类以及启动方式

《Android里面的Service种类以及启动方式》Android中的Service分为前台服务和后台服务,前台服务需要亮身份牌并显示通知,后台服务则有启动方式选择,包括startService和b... 目录一句话总结:一、Service 的两种类型:1. 前台服务(必须亮身份牌)2. 后台服务(偷偷干

C++实现封装的顺序表的操作与实践

《C++实现封装的顺序表的操作与实践》在程序设计中,顺序表是一种常见的线性数据结构,通常用于存储具有固定顺序的元素,与链表不同,顺序表中的元素是连续存储的,因此访问速度较快,但插入和删除操作的效率可能... 目录一、顺序表的基本概念二、顺序表类的设计1. 顺序表类的成员变量2. 构造函数和析构函数三、顺序表

Go语言利用泛型封装常见的Map操作

《Go语言利用泛型封装常见的Map操作》Go语言在1.18版本中引入了泛型,这是Go语言发展的一个重要里程碑,它极大地增强了语言的表达能力和灵活性,本文将通过泛型实现封装常见的Map操作,感... 目录什么是泛型泛型解决了什么问题Go泛型基于泛型的常见Map操作代码合集总结什么是泛型泛型是一种编程范式,允

Android kotlin语言实现删除文件的解决方案

《Androidkotlin语言实现删除文件的解决方案》:本文主要介绍Androidkotlin语言实现删除文件的解决方案,在项目开发过程中,尤其是需要跨平台协作的项目,那么删除用户指定的文件的... 目录一、前言二、适用环境三、模板内容1.权限申请2.Activity中的模板一、前言在项目开发过程中,尤

Android数据库Room的实际使用过程总结

《Android数据库Room的实际使用过程总结》这篇文章主要给大家介绍了关于Android数据库Room的实际使用过程,详细介绍了如何创建实体类、数据访问对象(DAO)和数据库抽象类,需要的朋友可以... 目录前言一、Room的基本使用1.项目配置2.创建实体类(Entity)3.创建数据访问对象(DAO

轻松掌握python的dataclass让你的代码更简洁优雅

《轻松掌握python的dataclass让你的代码更简洁优雅》本文总结了几个我在使用Python的dataclass时常用的技巧,dataclass装饰器可以帮助我们简化数据类的定义过程,包括设置默... 目录1. 传统的类定义方式2. dataclass装饰器定义类2.1. 默认值2.2. 隐藏敏感信息

Go信号处理如何优雅地关闭你的应用

《Go信号处理如何优雅地关闭你的应用》Go中的优雅关闭机制使得在应用程序接收到终止信号时,能够进行平滑的资源清理,通过使用context来管理goroutine的生命周期,结合signal... 目录1. 什么是信号处理?2. 如何优雅地关闭 Go 应用?3. 代码实现3.1 基本的信号捕获和优雅关闭3.2

C#如何优雅地取消进程的执行之Cancellation详解

《C#如何优雅地取消进程的执行之Cancellation详解》本文介绍了.NET框架中的取消协作模型,包括CancellationToken的使用、取消请求的发送和接收、以及如何处理取消事件... 目录概述与取消线程相关的类型代码举例操作取消vs对象取消监听并响应取消请求轮询监听通过回调注册进行监听使用Wa

Android WebView的加载超时处理方案

《AndroidWebView的加载超时处理方案》在Android开发中,WebView是一个常用的组件,用于在应用中嵌入网页,然而,当网络状况不佳或页面加载过慢时,用户可能会遇到加载超时的问题,本... 目录引言一、WebView加载超时的原因二、加载超时处理方案1. 使用Handler和Timer进行超