[英]DiffUtil is not updating the RecyclerView
我為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答案,但是都沒有用。 請幫忙
如果您在源代碼檢查ListAdapter
如何submitList
工作,你會發現這部分代碼:
if (newList == mList) {
// nothing to do (Note - still had to inc generation, since may have ongoing work)
return;
}
因此,除非您使用相同的引用傳遞列表,否則您將永遠不會更新列表。 要使其工作,您可以簡單地調用:
adapter.submitList(list.toList())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.