Reputation:
I have a ListView
of CardViews
. As you can see in the picture below, my cards have a vertical ImageView
on the edge with gray default background. I want to change the color of that ImageView
's background dynamically based on if the item is currently selected or not. I'm using ViewBinding
, so, the reference to my ImageView
would be binding.hightlightView
.
This is the code for my adapter:
class SectionListAdapter(private val onItemClicked: (Section) -> Unit) :
ListAdapter<Section, SectionListAdapter.SectionViewHolder>(DiffCallback()) {
private lateinit var binding: SectionItemViewBinding
private lateinit var parentBinding: FragmentSectionBinding
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SectionViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
binding = SectionItemViewBinding.inflate(layoutInflater, parent, false)
parentBinding = FragmentSectionBinding.inflate(layoutInflater)
return SectionViewHolder(binding)
}
override fun onBindViewHolder(holder: SectionViewHolder, position: Int) {
val currentItem = getItem(position)
holder.itemView.setOnClickListener {
onItemClicked(currentItem)
}
holder.bind(currentItem)
}
class SectionViewHolder(private val binding: SectionItemViewBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(item: Section) {
binding.apply {
sectionItemTitle.text = item.name
generalPriceValue.text = item.priceNationalCard.toString()
membersPriceValue.text = item.priceMembershipCard.toString()
}
}
}
class DiffCallback : DiffUtil.ItemCallback<Section>() {
override fun areItemsTheSame(oldItem: Section, newItem: Section): Boolean {
return newItem.id == oldItem.id
}
override fun areContentsTheSame(oldItem: Section, newItem: Section): Boolean {
return newItem == oldItem
}
}
}
Upvotes: 0
Views: 60
Reputation: 141
You can update the section object with the onItemClicked listener with a flag like selected and update the adapter again with notifyDataSetChanged. Then in your binding look for this flag to select or deselect the item.
Upvotes: 0