如何通过ID删除recyclerview项目?

时间:2020-02-07 22:19:20

标签: android kotlin android-recyclerview

我已经在顶视图中显示了数据。而且我不想在recyclerview上显示该数据。我该怎么办?


这是我用于删除项目的适配器,但不起作用。


override fun onBindViewHolder(holder: ViewHolder, position: Int) {

    val data = this.item?.get(position)

    val id_data= data!!.idberita.toString()

    if(sharedPrefDetailBerita.spIdberita == id_data){
        removeItem(data)
    }
}

private fun removeItem( infoData: ModelAuthor?) {
    val currPosition = this.item!!.indexOf(infoData)
    item!!.removeAt(currPosition)
    notifyItemRemoved(currPosition)
}

1 个答案:

答案 0 :(得分:0)

首先将其从您的list中删除:

 yourList.remove(getAdapterPosition());

然后使用它:

 notifyItemRemoved(getAdapterPosition());

至少用recyclerview更新您的notifyItemRangeChanged

notifyItemRangeChanged(getAdapterPosition(),yourList.size());

然后将您的remove function更改为:

private fun removeItem( infoData: ModelAuthor?) {

    item.remove(getAdapterPosition())
    notifyItemRemoved(getAdapterPosition())
    notifyItemRangeChanged(getAdapterPosition(),item.size())
}

更新:

onBindViewHolder中:

deletedata(data,holder)

onBindViewHolder中通过holder,然后像这样使用它:

private fun deletedata(infoData: ModelAuthor?,holder: ViewHolder){

    item!!.removeAt(holder.adapterPosition)
    notifyItemRemoved(holder.adapterPosition)
    notifyItemRangeChanged(holder.adapterPosition, item!!.size)
}