【发布时间】:2018-07-10 13:13:33
【问题描述】:
是否可以在下载新图像时在 Glide 中将之前下载的图像显示为占位符。
就像我在 imageview 中使用 glide 加载了一个图像。现在 imageurl 已更改,因此在加载此新图像时可以继续显示旧图像(可能来自缓存)。
我想要的是在从 URL 加载新图像时,是否可以将当前图像保留为占位符。
【问题讨论】:
标签: android android-glide
是否可以在下载新图像时在 Glide 中将之前下载的图像显示为占位符。
就像我在 imageview 中使用 glide 加载了一个图像。现在 imageurl 已更改,因此在加载此新图像时可以继续显示旧图像(可能来自缓存)。
我想要的是在从 URL 加载新图像时,是否可以将当前图像保留为占位符。
【问题讨论】:
标签: android android-glide
我在这里的讨论中找到了答案 - https://github.com/bumptech/glide/issues/527#issuecomment-148840717。
直觉上我也想过使用placeholder(),但问题是一旦加载第二张图片,就会失去对第一张图片的引用。您仍然可以引用它,但它不安全,因为它可能会被 Glide 重复使用或回收。
讨论中提出的解决方案是使用thumbnail() 并再次加载第一个图像。加载将立即从内存缓存中返回第一个图像,并且看起来图像在加载第二个图像之前没有更改:
String currentImageUrl = ...;
String newImageUrl = ...;
Glide.with(this)
.load(newImageUrl)
.thumbnail(Glide.with(this)
.load(currentImageUrl)
.fitCenter()
)
.fitCenter()
.into(imageView);
【讨论】:
Glide 能够从该 url 获取图像的位图,因此只需获取它,然后将其保存到所需的存储到您的手机中,然后在您的 .placeholder() 中使用该位图尝试获取另一个图像,看看这个sn-p
/** Download the image using Glide **/
Bitmap theBitmap = null;
theBitmap = Glide.
with(YourActivity.this).
asBitmap().
load("Url of your image").
into(-1, -1).
get(); //with this we get the bitmap of that url
saveToInternalStorage(theBitmap, getApplicationContext(), "your preferred image name");
/** Save it on your device **/
public String saveToInternalStorage(Bitmap bitmapImage, Context context, String name){
ContextWrapper cw = new ContextWrapper(context);
// path to /data/data/yourapp/app_data/imageDir
String name_="foldername"; //Folder name in device android/data/
File directory = cw.getDir(name, Context.MODE_PRIVATE);
// Create imageDir
File mypath=new File(directory,name_);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
Log.e("absolutepath ", directory.getAbsolutePath());
return directory.getAbsolutePath();
}
/** Method to retrieve image from your device **/
public Bitmap loadImageFromStorage(String path, String name)
{
Bitmap b;
String name_= name; //your folderName
try {
File f=new File(path, name_);
b = BitmapFactory.decodeStream(new FileInputStream(f));
return b;
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
return null;
}
/** Retrieve your image from device and set to imageview **/
//Provide your image path and name of the image your previously used.
Bitmap b= loadImageFromStorage(String path, String name)
ImageView img=(ImageView)findViewById(R.id.your_image_id);
img.setImageBitmap(b);
【讨论】: