如何使用Glide结合Drawable资源文件实现图标动画?
使用Glide结合Animated Drawable实现加载图标动画
嘿,我来帮你搞定这个问题!你已经写了一个animated-rotate的Drawable,这步走得很对,接下来只需要用Glide正确加载它,就能让你的加载图标转起来啦。下面是具体的操作步骤:
1. 先确认Glide依赖已配置
首先得确保你的项目里已经引入了Glide的依赖,打开Module级别的build.gradle(或者build.gradle.kts),添加以下代码:
// Groovy版本 implementation 'com.github.bumptech.glide:glide:4.16.0' annotationProcessor 'com.github.bumptech.glide:compiler:4.16.0' // Kotlin DSL版本 implementation("com.github.bumptech.glide:glide:4.16.0") kapt("com.github.bumptech.glide:compiler:4.16.0")
版本可以换成最新的稳定版,上面这个是经过验证的可靠版本。
2. 用Glide加载你的动画Drawable
你的animated-rotate Drawable本身就自带旋转动画,Glide可以直接加载它。只需要几行代码:
Kotlin示例:
Glide.with(this) // 这里的context可以是Activity、Fragment或者View .load(R.drawable.your_animated_drawable_name) // 替换成你那个animated-rotate的Drawable文件名 .into(yourLoadingImageView) // 替换成你的ImageView实例
Java示例:
Glide.with(this) .load(R.drawable.your_animated_drawable_name) .into(yourLoadingImageView);
3. 如果动画没自动启动?手动触发一下
有时候Glide加载完成后,动画Drawable可能不会自动开始播放,这时候可以通过Glide的监听回调手动启动动画:
Kotlin示例:
Glide.with(this) .load(R.drawable.your_animated_drawable_name) .listener(object : RequestListener<Drawable> { override fun onLoadFailed( e: GlideException?, model: Any?, target: Target<Drawable>?, isFirstResource: Boolean ): Boolean { // 加载失败的处理,这里返回false让Glide继续处理错误 return false } override fun onResourceReady( resource: Drawable?, model: Any?, target: Target<Drawable>?, dataSource: DataSource?, isFirstResource: Boolean ): Boolean { // 资源加载完成后,启动动画 (resource as? Animatable)?.start() return false // 返回false让Glide把资源设置到ImageView上 } }) .into(yourLoadingImageView)
4. 优化你的Drawable(可选)
你提供的Drawable代码是没问题的:
<?xml version="1.0" encoding="utf-8"?> <animated-rotate xmlns:android="http://schemas.android.com/apk/res/android" android:drawable="@drawable/loadingicon" android:pivotX="50%" android:pivotY="50%"> </animated-rotate>
如果想调整旋转速度,可以添加android:duration属性,比如android:duration="1000"表示1秒完成一圈旋转,数值越小转得越快。
内容的提问来源于stack exchange,提问作者DSoni
相关产品推荐
相关产品推荐

