Glide入门教程(18)动态使用 Model Loaders

       上篇文章讲了如何声明和创建一个可以添加图片大小到请求里的Glide module。这是非常强大的优化。然而,重要的是声明Glide module总是主动的。默认情况下,你不能动态开启或关闭他们。

       在本文中,会学习如何为单独的请求在网络上注册一个自定义model loader。

自定义图片大小

       快速回顾一下:通常Glide请求是从GlideUrl类中生成。上篇文章,我们展示了如何创建一个新的接口,额外将宽度和高度添加到考虑范围:

1
2
3
public interface CustomImageSizeModel {  
String requestCustomSizeUrl(int width, int height);
}

       创建了它的一个实例,向我们的Future Studio服务器传递了额外尺寸图片的URL。

1
2
3
4
5
6
7
8
9
10
11
12
13
public static class CustomImageSizeModelFutureStudio implements CustomImageSizeModel {

String baseImageUrl;

public CustomImageSizeModelFutureStudio(String baseImageUrl) {
this.baseImageUrl = baseImageUrl;
}

@Override
public String requestCustomSizeUrl(int width, int height) {
return baseImageUrl + "?w=" + width + "&h=" + height;
}
}

       最后,我们必须创造customimagesizeurlloader,传递高度和宽度到我们model的实现:

1
2
3
4
5
6
7
8
9
10
public static class CustomImageSizeUrlLoader extends BaseGlideUrlLoader<CustomImageSizeModel> {  
public CustomImageSizeUrlLoader(Context context) {
super( context );
}

@Override
protected String getUrl(CustomImageSizeModel model, int width, int height) {
return model.requestCustomSizeUrl( width, height );
}
}

Model Loaders的.using()的动态使用

       目前为止,我们上面的代码声明的Glide module,Glide会为每个单独的请求使用它。如果你不希望通过在AndroidManifest.xml里移除配置来关闭你的Glide module。我们可以这样做——Glide提供了.using()方法为一个单独请求去指定一个模型:

1
2
3
4
5
6
7
8
String baseImageUrl = "https://futurestud.io/images/example.png";  
CustomImageSizeModel customImageRequest = new CustomImageSizeModelFutureStudio( baseImageUrl );

Glide
.with( context )
.using( new CustomImageSizeUrlLoader( context ) )
.load( customImageRequest )
.into( imageView1 );

       正如上面所见,我们为加载优化尺寸的图片,创建了一个CustomImageSizeModelFutureStudio对象。由于没有在Glide module里声明CustomImageSizeModel接口,我们必须在上一行用.using(new CustomImageSizeUrlLoader( context ) )方法指定它。Glide会只为这个请求使用这个模型。其它的所有请求,即使它们也从CustomImageSizeModel实例构建,也不生效。

参考资料:
签到钱就到 Glide入门教程——20.动态使用 Model Loaders

Fork me on GitHub