[英]update list to recyclerview adapter with DiffUtil removing the old one?
我正在为我的 RecyclerView 使用 DiffUtil,它适用于一个加载列表,但是当尝试使用它来将新列表更新为当前列表时,它会删除旧数据,这是我的适配器
class SettingRecyclerView(private val interaction: Interaction? = null) :
RecyclerView.Adapter<RecyclerView.ViewHolder>() {
val DIFF_CALLBACK = object : DiffUtil.ItemCallback<SettingItem>() {
override fun areItemsTheSame(oldItem: SettingItem, newItem: SettingItem): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: SettingItem, newItem: SettingItem): Boolean {
return oldItem.hashCode() == newItem.hashCode()
}
}
private val differ = AsyncListDiffer(this, DIFF_CALLBACK)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return SettingViewHolder(
ItemRvBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
),
interaction
)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when (holder) {
is SettingViewHolder -> {
holder.bind(differ.currentList.get(position))
}
}
}
override fun getItemCount(): Int {
return differ.currentList.size
}
fun submitList(list: List<SettingItem>) {
differ.submitList(list)
}
class SettingViewHolder
constructor(
private val binding: ItemRvBinding,
private val interaction: Interaction?
) : RecyclerView.ViewHolder(binding.root) {
fun bind(item: SettingItem) = with(binding.root) {
binding.root.setOnClickListener {
interaction?.onItemSelected(adapterPosition, item)
}
binding.settingTitle.text = item.title
}
}
interface Interaction {
fun onItemSelected(position: Int, item: SettingItem)
}
}
这是我在我的活动中更新列表的方法
lateinit var mAdapter: SettingRecyclerView
mAdapter.submitList(settings)
我不知道究竟是什么问题导致了这个问题,还有其他方法可以使用 DiffUtil 更新列表,或者我必须使用 notifiydatachanged 还是什么?
如果您不使用data class
它将导致问题。
问题是您正在比较areContentsTheSame()
方法中的SettingItem.hashCode()
。
override fun areContentsTheSame(oldItem: SettingItem, newItem: SettingItem): Boolean {
\\ You need to pass the same object to evaluate to true.
return oldItem.hashCode() == newItem.hashCode()
}
解决方案:
您需要以正确的方式使用data class
,以便编译器自动从主构造函数中声明的所有属性派生hashCode()
和equals()
。
看到这个:数据类
或者您应该手动比较SettingsItem
的属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.