在RecyclerViewAdapter中使用Glide从Firebase存储加载图像

时间:2018-07-25 11:35:02

标签: android firebase android-recyclerview firebase-storage android-glide

我使用GlideFirebase Storage中的RecyclerViewAdapter加载图像。

问题是,有时会加载所有图像,但是当我向上或向下滚动时,图像会消失,并且可能会再次出现,但可能不会。并且也可能只加载第一个图像。如何避免这种情况

这是我的model

private String name;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

这是我的MainActivity

imageNames.add(0,"first.jpg");
    imageNames.add(1,"second.jpg");
    imageNames.add(2,"third.jpg");
    imageNames.add(3,"fourth.jpg");

    for(int i=0;i<imageNames.size();i++) {
        StorageReference ref = storageReference.child("filee/" + imageNames.get(i));
        ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
            @Override
            public void onSuccess(Uri uri) {
                String imageURL = uri.toString();
                ImageClass imageClass = new ImageClass();
                imageClass.setName(imageURL);
                list.add(imageClass);
                recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));

                Toast.makeText(MainActivity.this, "Downloaded", Toast.LENGTH_SHORT).show();

            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception exception) {
                Toast.makeText(MainActivity.this, "Not Downloaded", Toast.LENGTH_SHORT).show();
            }
        });

    }
      adapter = new ImageRecyclerAdapter(MainActivity.this,list);
        recyclerView.setAdapter(adapter);

这是我的adapter

ublic class ImageRecyclerAdapter extends RecyclerView.Adapter<ImageRecyclerAdapter.myViewHolder> {

List<ImageClass> myClassImageList;
Context context;
public ImageRecyclerAdapter(Context context,List<ImageClass> imageClassArrayList) {
    this.myClassImageList = imageClassArrayList;
    this.context=context;
}

@Override
public myViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View row = LayoutInflater.from(parent.getContext()).inflate(R.layout.image_layout,parent,false);
    myViewHolder myViewHolder = new myViewHolder(row);
    return myViewHolder;
}

@Override
public void onBindViewHolder(myViewHolder holder, int position) {
    ImageClass imageClass = myClassImageList.get(position);
    if(myClassImageList.get(position).getName()!=null) {
        Glide.with(context).load(imageClass.getName()).into(holder.imageView);
    }
    else {
        Glide.clear(holder.imageView);
        holder.imageView.setImageDrawable(null);

    }
}

//....

0 个答案:

没有答案