I'm trying to create a RecyclerView that having checkbox in each of its item. I followed this link to save states of checkbox, that is to add a boolean variable to my object. However, I encountered a problem that the value of isChecked
from my object cannot be changed. Is the content of currentList
immutable? Is there any way for me to implement this feature with ListAdapter?
Here is the snippet of my code. Thank you very much.
class DocumentAdapter() : ListAdapter<Document, DocumentAdapter.DocumentViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DocumentViewHolder {
return LayoutInflater.from(parent.context)
.inflate(R.layout.item_document, parent, false)
.let {
DocumentViewHolder(it)
}
}
override fun onBindViewHolder(holder: VH, position: Int) {
holder.bind(getItem(position))
}
class DocumentViewHolder(
override val view: View
) : RecyclerView.ViewHolder<DocumentDTO>(view) {
fun bind(item: Document) {
cbItem.isChecked = item.isChecked
cbItem.setOnCheckedChangeListener { _, isChecked ->
item.isChecked = isChecked // Not working
}
}
}
}
When debugging, after running through the line item.isChecked = isChecked
, I can see value isChecked
inside currentList
is not updated, even though that value of the local Document
item has been updated.
Since mutation to content of ListAdapter must be submitted through submitList(), I have to create a callback and send the updated item out to update the data.
fun bind(item: Document) {
cbItem.isChecked = item.isChecked
cbItem.setOnCheckedChangeListener { _, isChecked ->
item.isChecked = isChecked
onCheckBoxClicked(item, isChecked)
}
}