I'm trying to check multiple items in RecyclerView and delete them but unable to delete after checking CheckBox in custom RecyclerViewAdapter.
class TestAdapter(var isSelectingEnabled: Boolean) : RecyclerViewBaseAdapter<TestModel>() {
val selectedList: ArrayList<TestModel>? = null
override fun getLayoutResId(viewType: Int): Int = R.layout.test_list_item
var onItemClick: ((TestModel) -> Unit)? = null
override fun bindData(
holder: SimpleViewHolder<TestModel>,
model: TestModel,
position: Int
) {
val context = holder.itemView.context
val checkBox = holder.itemView.findViewById<MaterialCheckBox>(R.id.checkbox)
holder.itemView.setOnClickListener {
onItemClick?.invoke(model)
}
checkBox.apply {
checkBox.setOnCheckedChangeListener(null)
checkBox.isChecked = model.isSelected
isVisible = isSelectingEnabled
setOnCheckedChangeListener { buttonView, isChecked ->
selectedList?.add(model)
}
}
}
}
In Fragment:
private fun removeListItems() {
if (!testAdapter.isSelectingEnabled) {
testAdapter.removeAllItems(arrayList)
arrayList.clear()
binding.buttonBulkAddRemove.isEnabled = false
} else {
if (arrayList.size > 0) {
testAdapter.selectedList?.forEach {
if (arrayList.contains(it)) {
testAdapter.removeItems(it)
arrayList.remove(it)
}
}
}
}
}
Defined few methods in BaseAdapter class as:
fun removeItems(model: T): Boolean {
val index = dataList.indexOf(model)
val removed = dataList.remove(model)
if (removed) {
notifyItemRemoved(index)
}
return removed
}
fun removeAllItems(listItems: List<T>) {
dataList.removeAll(listItems)
notifyDataSetChanged()
}
Please guide me if I'm doing anything wrong.