更新列表适配器

时间:2019-07-31 06:39:09

标签: android listadapter

我无法在android中的listAdapter中更新数据

我的适配器:

class Adapter(val viewModel: ConfirmViewModel,
              private val uiDownloadManager: UiDownloadManager)
    : ListAdapter<Comment, RecyclerView.ViewHolder>(MessageListDiffUtil()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val viewItem = LayoutInflater.from(parent.context)
                .inflate(R.layout.confirm_comment, parent, false)
        return CommentHolder(viewItem)
    }

    override fun onBindViewHolder(viewHolder: RecyclerView.ViewHolder, position: Int) {
        try {
            viewHolder as CommentHolder
            viewHolder.bind(getItem(position), uiDownloadManager)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

}

class MessageListDiffUtil : DiffUtil.ItemCallback<Comment>() {
    override fun areItemsTheSame(p0: Comment, p1: Comment): Boolean {
        return p0.serverId == p1.serverId
    }
    override fun areContentsTheSame(p0: Comment, p1: Comment): Boolean {
        return p0.serverId == p1.serverId
    }
}

更新代码:

val c = Comment()
c.serverId = 5
c.text = "for test"
val l = listOf(c)
adapter.submitList(l)

在recyclerview中不显示任何数据 发生了什么事,当适配器第一次不提交所有项目时调用submitList

1 个答案:

答案 0 :(得分:0)

我认为这与您的Diff项目回调有关,尝试添加更多的比较,而不仅仅是ID。像这样

class MessageListDiffUtil : DiffUtil.ItemCallback<Comment>() {
    override fun areItemsTheSame(p0: Comment, p1: Comment): Boolean {
        return p0.serverId == p1.serverId && p0.something == p1.something ......
    }
    override fun areContentsTheSame(p0: Comment, p1: Comment): Boolean {
        return p0.serverId == p1.serverId && p0.commentText == p1.commentText .....
    }
}

在某些情况下,还需要重写ListAdapter中的SubmitList():

 override fun submitList(list: List<SomeModel>?) {
        if (list != null) {
            super.submitList(ArrayList(list))
        } else {
            super.submitList(null)
        }
    }