I have question, I want to make an item clicked in recyclerview, in adapter class I used the below method for define item clicked:
var onItemClick: ((ResponseGetDate) -> Unit)? = null
ResponseGetDate is the data class
also in the viewHolder (inner class) I used above variable for defining item clicked:
holder.itemView.setOnClickListener {
onItemClick?.invoke(itemDate)
}
itemData is an item of ResponseGetDate class
Now, in the main activity or fragment when I build an instance from the adapter class, I can click on each item. see the code below:
adapterGetDate.onItemClick = { dateItem ->
}
The question is: if I want to click on each item, the item must be selected. and if I click on the another item, previous item must be deselected and the new one be selected. How can I do this?
Single item selection can be maintained in RecyclerView by
Background drawable For the item selected in my example:
Drawable name: bg_capsule_selected
For the item unselected
Drawable name: bg_capsule_unselected
Variables
Two variables to be initialized in your Adapter Class
Separate methods in the ViewHolder Class for changing the background of the items when selected and unselected
Logic The logic is to update the variables and calling the
notifyItemChange(position)which would then call the methodonBindViewHolder(holder: ViewHolder, position: Int)for this to happen we have to initialize the click listener for each of theitemViewsand update the variables accordingly with the adapter position and callnotifyItemChange()method with passing the item position to changethis code is written inside the ViewHolder Class as an init block Since we have set click listeners for every
itemViewand then when we callnotifyItemChange()method would callonBindViewHolder()method and in this method, we would check for the position and change their background with the help of two methods written inside ViewHolder Class like this