背景
recyclerview中,IamgeView的高度根據(jù)glide加載圖片返回的寬高進(jìn)行配置,會偶發(fā),glide加載生成的drawable寬高混亂,代碼如下:
Glide.with(context.getApplicationContext())
.load(img == null ? t : img)
.apply(options)
.addListener(new RequestListener<Drawable>() {
@Override
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
if (listener != null) {
listener.onLoadFailed(e, model, target, isFirstResource);
}
return false;
}
@Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
if (listener != null) {
listener.onResourceReady(resource, model, target, dataSource, isFirstResource);
}
return false;
}
})
.into(imageView);
實(shí)際開發(fā)中,發(fā)現(xiàn)onResourceReady的resource,寬高會偶發(fā)錯亂,因此,換一種方法實(shí)現(xiàn),內(nèi)容如下:
Glide.with(context.getApplicationContext())
.asBitmap()
.load(img == null ? t : img)
.apply(options)
.into(new CustomTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
if (listener != null) {
int width = resource.getWidth();
int height = resource.getHeight();
LogUtils.d("onResourceReady url: " + finalImg + " width: " + width + " height: " + height);
listener.ready((width >= height), width, height, resource);
}
}
@Override
public void onLoadCleared(@Nullable Drawable placeholder) {
if (listener != null) {
listener.loadFailed();
}
}
});
這種情況下,bitmap經(jīng)過實(shí)測,它的寬高是準(zhǔn)確的,所以目前換成了這種方法實(shí)現(xiàn)。
原因是因?yàn)閞ecyclerview中,imageview的復(fù)用問題,導(dǎo)致了drawable的問題,最后加載完圖片也是有問題的。該問題需要結(jié)合復(fù)用,與ImageView進(jìn)行思路。