2

请帮帮我。
我使用Coil在网格 RecyclerView 中显示图像。
实现非常简单——在viewholder.bind()我调用的每一个中image.load(URL)
URL是静态URL = "https://loremflickr.com/200/200/"的,只是在每个请求上提供一个新的随机图片。在应用程序启动
时创建持有者时,工作得很好,为每个持有者加载新图像。问题:当我开始滚动回收器时,只获取最新下载的图片而不是下载新图片。我曾经看到它只对第一部分持有者执行真正的 http 调用。问题RecyclerViewimage.load(URL)
image.load(URL)loggerInterceptorimage.load(URL)
:如何让 Coil 为 recyclerView 中的每个查看者下载新图片,而不仅仅是第一组可见的持有者?

在此处输入图像描述

持有人:

class ImageViewHolder(val binding: ItemImageBinding) : RecyclerView.ViewHolder(binding.root) {
 
    fun bind() {
        binding.image.load(URL){}
    }
 
    companion object {
        fun create(parent: ViewGroup): ImageViewHolder {
            val layoutInflater = LayoutInflater.from(parent.context)
            val binding = ItemImageBinding.inflate(layoutInflater)
            return ImageViewHolder(binding)
        }
    }
}

适配器:


class ImageRvAdapter(val list: MutableList<ImageModel>) : ListAdapter<ImageModel, ImageViewHolder>(
    IMAGE_COMPARATOR
) {
 
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ImageViewHolder {
        return ImageViewHolder.create(parent)
    }
 
    override fun onBindViewHolder(holder: ImageViewHolder, position: Int) {
        holder.bind()
    }
 
    companion object {
        val IMAGE_COMPARATOR = object : DiffUtil.ItemCallback<ImageModel>() {
            override fun areItemsTheSame(oldItem: ImageModel, newItem: ImageModel): Boolean {
                return newItem::class == oldItem::class
            }
 
            override fun areContentsTheSame(oldItem: ImageModel, newItem: ImageModel): Boolean {
                return oldItem == newItem
            }
        }
    } }

适配器设置:

   //Data model for list
    sealed class ImageModel{
        object Image:ImageModel()
    }
    //Adapter setup
    lateinit var adatper: ImageRvAdapter
    private fun initRecyclerView() {
        //creating a list of 140 items
        val imageList: MutableList<ImageModel> = mutableListOf()
        for (i in 0..139){  
            imageList.add(ImageModel.Image)
        }
        //adapter stuff
        adatper = ImageRvAdapter()
        binding.recyclerView.layoutManager = GridLayoutManager(
            this,
            6,
            GridLayoutManager.HORIZONTAL,
            false
        )
        binding.recyclerView.adapter = adatper
        adatper.submitList(imageList) 
    }
4

0 回答 0