一、起因
旧版本Glide
中.signature()
方法形参支持使用StringSignature
。但在Glide 4.0
里面这个方法不仅被移到RequestOptions
中,而且形参改为Key
。
不过Key
是一个接口,需要实现抽象方法
void updateDiskCacheKey(MessageDigest messageDigest);
Key
还有一个使用相对方便的子类ObjectKey
,构造方法以Object
为参数,下面是实际用法:
public static RequestOptions userAvatarOptions = new RequestOptions()
.placeholder(R.drawable.def_avatar)
.error(R.drawable.def_avatar)
.signature(new ObjectKey(System.currentTimeMillis()))
.encodeQuality(70);
代码中创建了一个ObjectKey
实例,并把当前时间戳整形值作为参数。
顺便贴出Key
和ObjectKey
的源码,请自行查阅:
public interface Key {
String STRING_CHARSET_NAME = "UTF-8";
Charset CHARSET = Charset.forName(STRING_CHARSET_NAME);
void updateDiskCacheKey(MessageDigest messageDigest);
@Override
boolean equals(Object o);
@Override
int hashCode();
}
public final class ObjectKey implements Key {
private final Object object;
public ObjectKey(Object object) {
this.object = Preconditions.checkNotNull(object);
}
@Override
public String toString() {
return "ObjectKey{"
+ "object=" + object
+ '}';
}
@Override
public boolean equals(Object o) {
if (o instanceof ObjectKey) {
ObjectKey other = (ObjectKey) o;
return object.equals(other.object);
}
return false;
}
@Override
public int hashCode() {
return object.hashCode();
}
// Charset CHARSET = Charset.forName("UTF-8");
@Override
public void updateDiskCacheKey(MessageDigest messageDigest) {
messageDigest.update(object.toString().getBytes(CHARSET));
}
}
StringSignature class not found #2692
最终解决方案
RequestOptions userAvatarOptions = new RequestOptions()
// .placeholder(R.drawable.def_avatar)
// .error(R.drawable.def_avatar)
.signature(new ObjectKey(System.currentTimeMillis()));
Glide.with(ProfileActivity.this).applyDefaultRequestOptions(userAvatarOptions).load(iamgePath).apply(RequestOptions.bitmapTransform(new CircleCrop())).
into(mIvApHeader);