gpt4 book ai didi

android - DiffUtil 没有更新 RecyclerView

转载 作者:行者123 更新时间:2023-12-05 00:09:57 26 4
gpt4 key购买 nike

我为 recyclerView 制作了一个适配器,并使用 DiffUtil 以更漂亮的方式显示列表的更新。我使用 google codelabs 作为引用。但该列表并未从以下代码更新。请帮忙

class LaptopAdapter : ListAdapter<Laptop, LaptopAdapter.ViewHolder>(Diff()) {

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder.from(parent)
}

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = getItem(position)
holder.bind(item)
}

class ViewHolder private constructor(itemView: View) : RecyclerView.ViewHolder(itemView) {
var ramText: TextView = itemView.findViewById(R.id.ramText)
var diskText: TextView = itemView.findViewById(R.id.diskText)
var screenText: TextView = itemView.findViewById(R.id.screenText)
var osText: TextView = itemView.findViewById(R.id.osText)

fun bind(item: Laptop) {
ramText.text = item.ram.toString()
diskText.text = item.disk
screenText.text = item.screen.toString()
osText.text = item.os
}

companion object {
fun from(parent: ViewGroup) =
ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item, parent, false))
}
}
}

class Diff : DiffUtil.ItemCallback<Laptop>() {
override fun areItemsTheSame(oldItem: Laptop, newItem: Laptop): Boolean {
return oldItem.id == newItem.id
}

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

我的 MainActivity 文件是
setContentView(R.layout.activity_main)

val list: ArrayList<Laptop> = ArrayList()
list.add(Laptop(11, 4, "SSD", 14, "Windows"))
list.add(Laptop(12, 4, "HDD", 14, "Ubuntu"))
list.add(Laptop(17, 16, "SSD", 14, "Windows"))
list.add(Laptop(13, 8, "SSD", 14, "Windows"))

val rv: RecyclerView = findViewById(R.id.rv)
rv.layoutManager = LinearLayoutManager(this)
val adapter = LaptopAdapter()
rv.adapter = adapter
adapter.submitList(list)

val btn: Button = findViewById(R.id.btn)
btn.setOnClickListener {
list.add(Laptop(15, 12, "HDD", 12, "DOS"))
list.sortBy {
it.ram
}
adapter.submitList(list)
}

我尝试了以前的 stackOverflow 答案,但没有一个有效。请帮忙

最佳答案

如果您 checkin ListAdapter 的源代码如何submitList工作你会发现这部分代码:

if (newList == mList) {
// nothing to do (Note - still had to inc generation, since may have ongoing work)
return;
}

因此,除非您通过具有相同引用的列表,否则您将永远不会更新您的列表。至
让它工作你可以简单地调用:
adapter.submitList(list.toList())

关于android - DiffUtil 没有更新 RecyclerView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56881149/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com