it's quite easy to do :) You need to just remember how the RecyclerView works:
- It creates few ViewHolders
- When you scroll your list, the ViewHolders are reused.
- If you have for example 100 items on the list, it will create 5-6 ViewHolders and will reuse them.
So having that in mind, when onBindViewHolder()
is called, the easiest thing you can do is to check some state of the item, and then choose background color of the item. In this scenario you can select/deselect multiple items in the list. If you want to have only one checked, you will need to change the items.map {}
function a little bit:
Please keep in mind that I wrote below from my head, you will also need to override some more functions in adapter etc.
class MyAdapter(private val onItemClick: (YouItem) -> Unit): RecyclerView.Adapter() {
private var items: List<YourItem>
fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val payload = items[holder.adapterPosition]
holder.itemView.setOnClickListener {
onItemClick(payload)
}
holder.itemView.background = if(payload.someState) firstBackground else otherBackground
}
fun updateItems(updatedItems: List<YourItem>) {
items = updatedItems
notifyDataSetChanged()
}
}
class YourActivity: Activity() {
private lateinit var items: List<YourItem>
fun onCreate(savedInstanceState: Bundle) {
super.onCreate(savedInstanceState)
...
items: List<YourItem> = getItemsFromSomewhere()
val adapter = MyAdapter { clickedItem ->
val updatedItems = items.map {
if(it == clickedItem) {
it.copy(someState = !it.someState)
} else {
it
}
items = updatedItems
adapter.updateItems(updatedItems)
}
}
}
data class YourItem(val someState: Boolean)