如何在ListAdapter中添加数据?

问题描述

listadapter 中,如何将数据添加到现有列表中?

submitList() 只会用新列表替换现有列表, 也许是一种更新数据的方法

adapter.addNewItem(list)

解决方法

不要修改 ListAdapter 中的数据,而是始终更新数据源,即您案例中的列表并将更新后的列表提交到 ListAdapter

//assume you have this either in your view model or where ever it is
val dataList = ArrayList<String>()

fun updateData(newData: List<Data>){
    dataList.addAll(newData) // add new data to existing data
    adapter.submitList(dataList) //submit the data again
}
,

您可以从适配器获取列表:

adapter.getCurrentList()

然后您需要创建一个副本,添加一个新项目,并将其提交给适配器。