Java 使用DiffUtil删除旧的recyclerview适配器更新列表?

Java 使用DiffUtil删除旧的recyclerview适配器更新列表?,java,android,list,kotlin,android-recyclerview,Java,Android,List,Kotlin,Android Recyclerview,我正在为我的RecyclerView使用DiffUtil,它可以很好地用于一个加载列表,但是当尝试将新列表更新为当前列表时,它会删除旧数据 这是我的适配器 class SettingRecyclerView(private val interaction: Interaction? = null) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { val DIFF_CALLBACK = object : Diff

我正在为我的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)
    }
}

我不知道到底是什么问题导致了这个问题,是否有其他方法可以使用DiffUtil更新列表,或者我必须使用notifiydatachanged或其他什么?

如果您不使用
数据类
,这将导致问题。

问题是您正在比较
方法中的
设置项。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()
}
解决方案:

您需要以正确的方式使用
数据类
,以便编译器自动从主构造函数中声明的所有属性派生
hashCode()
equals()

见此:

或者您应该手动比较
SettingsItem
的属性

override fun areContentsTheSame(oldItem: SettingItem, newItem: SettingItem): Boolean {
    \\ You need to pass the same object to evaluate to true.
    return oldItem.hashCode() == newItem.hashCode()
}