当我使用 AsyncListDiffer 和视图绑定时,适配器中没有任何显示

Nothing show in Adapter when I use AsyncListDiffer and view binding

我尝试使用视图绑定和 diffUtil

在自定义回收器视图中显示数据形式 api

我尝试在 RecyclerView 适配器中将 DiffUtil 与绑定视图一起使用 但是当我从片段 differ.submitList(DATA) 发送数据时 列表中没有显示

调试的时候发现数据来自API然后去differ

class NewsAdapter : RecyclerView.Adapter<NewsAdapter.ItemViewHolder>() {

private val differCallBack = object : DiffUtil.ItemCallback<Article>() {
    override fun areItemsTheSame(oldItem: Article, newItem: Article): Boolean {
        return oldItem.url == newItem.url
    }

    override fun areContentsTheSame(oldItem: Article, newItem: Article): Boolean {
        return oldItem == newItem
    }
}

val differ = AsyncListDiffer(this, differCallBack)


override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
    return ItemViewHolder(
        LayoutInflater.from(parent.context)
            .inflate(R.layout.item_article_preview, parent, false)
    )
}

inner class ItemViewHolder(private val view: View) :
    RecyclerView.ViewHolder(view) {
    var binding =
        ItemArticlePreviewBinding.bind(view)

    fun bind(article: Article) {
        Glide.with(view).load(article.urlToImage).into(binding.ivArticleImage)
        binding.tvTitle.text = article.title
        binding.tvSource.text = article.source.name
        binding.tvDescription.text = article.description
        binding.tvPublishedAt.text = article.publishedAt
    }
}


override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
    val article = differ.currentList[position]
    holder.itemView.apply {
        holder.bind(article)
        setOnClickListener {
            onItemClickListener?.let {
                it(article)
            }
        }
    }
}

private var onItemClickListener: ((Article) -> Unit)? = null

fun setOnClickListener(listener: (Article) -> Unit) {
    onItemClickListener = listener
}

override fun getItemCount(): Int {
    return differ.currentList.size
}

}

ItemViewHolder 中,您绑定数据的 itemView 和您传递给 recyclerViewitemView 是两个不同的视图。

您从 onCreateViewHolder 创建后传递给 ItemViewHolderview 正在传递给 RecyclerView,但您将数据绑定到另一个 view 您正在使用 ItemArticlePreviewBindingviewBinding 充气。

您可以更改 ViewHolder 的构造函数以接受 binding 实例而不是 view,然后将数据绑定到该 binding 对象。

inner class ItemViewHolder(private val binding: ItemArticlePreviewBinding) :
    RecyclerView.ViewHolder(binding.root) {

    fun bind(article: Article) {
        Glide.with(view).load(article.urlToImage).into(binding.ivArticleImage)
        binding.tvTitle.text = article.title
        binding.tvSource.text = article.source.name
        binding.tvDescription.text = article.description
        binding.tvPublishedAt.text = article.publishedAt
    }
}

onCreateViewHolder 内部膨胀一个 ViewBinding 对象并将其传递给 ItemViewHolder 的构造函数

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
    return ItemViewHolder(
        ItemArticlePreviewBinding.inflate(LayoutInflater.from(parent.context), parent, false)
    )
}