首先,在 ChildRecyclerView 中,为每个子项添加一个删除按钮或图标。
在适配器的 onBindViewHolder 方法中添加以下代码,以便在单击删除按钮时触发删除操作:
holder.btnDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int position = holder.getAdapterPosition();
// Remove the item from the data list
dataList.remove(position);
// Notify the adapter that an item has been removed at the specific position
notifyItemRemoved(position);
// Notify the adapter that the data at a specific position has been changed
notifyItemRangeChanged(position, getItemCount());
}
});
这里 dataList 是包含数据的列表,holder 是绑定子项视图的 holder 对象。使用 notifyItemRemoved 和 notifyItemRangeChanged 方法通知适配器数据已更改。
同时在适配器中添加以下方法,以便在主 RecyclerView 的删除操作中调用此方法:
public void removeItem(int position) {
// Remove the item from the data list
dataList.remove(position);
// Notify the adapter that an item has been removed at the specific position
notifyItemRemoved(position);
// Notify the adapter that the data at a specific position has been changed
notifyItemRangeChanged(position, getItemCount());
}
adapter.removeItem(position);