如果你用 Glide,通过网络连接加载图像。但网速有点慢,APP显示图片界面已经打开了,但是图片半天显示不出来,这样的空 ImageView 在任何 UI 上都是不好看的。让APP 去显示一个占位符直到这张图片加载处理完成,这样应该会缓解一部分用户急躁的情绪。
占位符
Glide 的流式接口让这个变得非常容易的去做到!只需要调用 .placeHolder()
用一个 drawable(resource) 引用,Glide 将会显示它作为一个占位符,直到你的实际图片准备好。
Glide
.with(context)
.load(UsageExampleListViewAdapter.eatFoodyImages[0])
.placeholder(R.mipmap.ic_launcher) // can also be a drawable
.into(imageViewPlaceholder);
做为一个显而易见的原因,你不能设置一个网络 url 作为占位符,因为这也会被去请求加载的。App 资源和 drawable 能保证可用和可访问的。然而,作为 load() 方法的参数,Glide 接受所有值。这可能不是可加载的(没有网络连接,服务器宕机…),删除了或者不能访问。在下一节中,我们将讨论一个错误的占位符。
错误占位符:.error()
如果给出的网络图片地址,访问不了(可能链接已经失效),应该显示一个错误占位符,告知用户,访问不了图片。
假设我们的 App 尝试从一个网站去加载一张图片。Glide 给我们一个选项去获取一个错误的回调并采取合适的行动。我们会在后面来讨论,对现在来说,可能太复杂了。在大多数情况下使用占位符,来指明图片不能被加载已经足够了。
调用 Glide 的流式接口和之前显示预加载占位符的例子是相同的,不同的是调用了名为 error()
的函数。
Glide
.with(context)
.load("http://futurestud.io/non_existing_image.png")
.placeholder(R.mipmap.ic_launcher) // can also be a drawable
.error(R.mipmap.future_studio_launcher) // will be displayed if the image cannot be loaded
.into(imageViewError);
就这样。如果你定义的 load()
值的图片不能被加载出来,Glide 会显示 R.mipmap.future_studio_launcher
作为替换。再说一次,error()
接受的参数只能是已经初始化的 drawable 对象或者指明它的资源(R.drawable.<drawable-keyword>)。
使用 crossFade()
简单的选项是让它改变是更加平滑和养眼的,就是使用一个淡入淡出动画。
Glide 使用标准的淡入淡出动画,这是(对于当前版本3.6.1)默认激活的。如果你想要强制 Glide 显示一个淡入淡出动画,你必须调用另外一个建造者:
Glide
.with(context)
.load(UsageExampleListViewAdapter.eatFoodyImages[0])
.placeholder(R.mipmap.ic_launcher) // can also be a drawable
.error(R.mipmap.future_studio_launcher) // will be displayed if the image cannot be loaded
.crossFade()
.into(imageViewFade);
crossFade()
方法还有另外重载方法 .crossFade(int duration)
。如果你想要去减慢(或加快)动画,随时可以传一个毫秒的时间给这个方法。动画默认的持续时间是 300毫秒。
使用 dontAnimate()
如果你想直接显示图片而没有任何淡入淡出效果,在 Glide 的建造者中调用 .dontAnimate()
。
Glide
.with(context)
.load(UsageExampleListViewAdapter.eatFoodyImages[0])
.placeholder(R.mipmap.ic_launcher) // can also be a drawable
.error(R.mipmap.future_studio_launcher) // will be displayed if the image cannot be loaded
.dontAnimate()
.into(imageViewFade);
这是直接显示你的图片,而不是淡入显示到 ImageView。请确保你有更好的理由来做这件事情。
需要知道的是所有这些参数都是独立的,而不需要彼此依赖的。比如,你可以设定 .error()
而不调用 .placeholder()
。你可能设置 crossFade()
动画而没有占位符。任何参数的组合都是可能的。
展望
希望你在这篇博客中理解并学到很多。这对于一个良好的用户体验是非常重要的,即图片不会没有预期的突然蹦出来。同样的,当有什么事情出错时,使其有明显的提示。Glide 协助你容易的去这些方法,提供的这些事情去帮你做一个更好的 App。
但是我们的优化还没有做完。图像大小和缩放也是不错的选择。