You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

RecyclerView列表数据更新时未刷新问题排查

RecyclerView添加元素后未更新的原因及解决方法

核心问题

你在addOBject方法中直接修改了原列表的内容,然后把同一个List实例传给了适配器。AsyncListDiffer内部会先判断新旧列表的引用是否相同,如果引用一致,就不会触发DiffUtil的对比逻辑,自然不会更新界面。

解决方案

1. 传递新的List实例给适配器

修改addOBject方法,每次添加元素时创建新的列表对象,避免复用原列表引用:

private fun addOBject() {
    // 创建新的列表实例,确保与原列表引用不同
    val newList = vehicleInformationList.toMutableList().apply {
        add(vehicleInformation)
    }
    vehicleInformationList = newList
    vehicleInvolvedAdapter.vehicleInformationList = newList
}

或者更简洁的写法:

private fun addOBject() {
    vehicleInformationList = vehicleInformationList + vehicleInformation
    vehicleInvolvedAdapter.vehicleInformationList = vehicleInformationList
}

2. 确保VehicleInformation的equals方法正确实现

你的diffCallback中areContentsTheSame使用了oldItem == newItem,如果VehicleInformation不是Kotlin数据类(data class),需要手动重写equals和hashCode方法,否则会默认比较对象引用,导致内容判断错误。

普通类重写示例:

class VehicleInformation(
    val id: String,
    val plateNumber: String
) {
    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (javaClass != other?.javaClass) return false

        other as VehicleInformation

        if (id != other.id) return false
        if (plateNumber != other.plateNumber) return false

        return true
    }

    override fun hashCode(): Int {
        var result = id.hashCode()
        result = 31 * result + plateNumber.hashCode()
        return result
    }
}

如果是数据类,Kotlin会自动生成正确的equals和hashCode,无需手动处理。

内容的提问来源于stack exchange,提问作者Ibanez1408

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 00:42:04