我有一个回收视图,可将存储在Firebase存储中的不同图像加载。当我滚动回收视图时,每次都会加载相同的图像(仅根据回收视图的定义)。
我如何一次下载这些图像并附加到回收视图,以使其在滚动时不应该重新加载?
我已经尝试过这样。
public void onBindViewHolder(final TodaysBdayViewHolder holder, int position)
{
storageReference=FirebaseStorage.getInstance().getReference().child("profiles/"+contacts.get(position)+".jpg");
final File localFile=File.createTempFile("profile_pic","jpeg",new File(context.getExternalFilesDir("null").getAbsolutePath()));
storageReference.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Log.i("app","FinishIntro Img loaded");
Bitmap bitmap= BitmapFactory.decodeFile(localFile.getAbsolutePath());
holder.FriendPhoto.setImageBitmap(bitmap);
}
}).addOnFailureListener(new OnFailureListener() {
public void onFailure(@NonNull Exception e) {
}
});
}
您可以使用glide缓存图像并将其显示在图像视图中
public void onBindViewHolder(final TodaysBdayViewHolder holder, int position)
{
storageReference = FirebaseStorage.getInstance().getReference().child("profiles/"+contacts.get(position)+".jpg");
// get the download URL
storageReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
public void onSuccess(Uri uri) {
// load and cache with glide
Glide.with(context)
.load(uri)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(holder.FriendPhoto);
}
}).addOnFailureListener(new OnFailureListener() {
public void onFailure(@NonNull Exception e) {
}
});
}
您正在通过自己从文件中解码位图,这不是很有效。相反,我建议使用一个库,该库旨在有效地执行Picasso或Glide这样的事情。
毕加索方法:
添加到gradle:
implementation 'com.squareup.picasso:picasso:2.71828'
并且在加载时执行此操作:
//the file
final File localFile=File.createTempFile("profile_pic","jpeg",new File(context.getExternalFilesDir("null").getAbsolutePath()));
//the reference
storageReference=FirebaseStorage.getInstance().getReference().child("profiles/"+contacts.get(position)+".jpg");
//the call
storageReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
// use this uri in picasso call into imageview
Picasso.get().load(uri.toString()).into(holder.FriendPhoto);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
// Handle any errors
}
});