Hi, I haven’t found the realization of this challenge with ViewBinding, so I propose mine. It’s working, but I would appreciate any suggestions for improvement.
The main challenging changes are in CrimeListAdapter, so I post only them:
open class Holder(
private val binding: ViewBinding
) : RecyclerView.ViewHolder(binding.root) {
open fun bind(crime: Crime) {
}
}
class CrimeHolder(
val bindingCrime: ListItemCrimeBinding
) : Holder(bindingCrime) {
override fun bind(crime: Crime) {
bindingCrime.crimeTitle.text = crime.title
bindingCrime.crimeDate.text = crime.date.toString()
bindingCrime.root.setOnClickListener {
Toast.makeText(
bindingCrime.root.context,
"${crime.title} clicked!",
Toast.LENGTH_SHORT
).show()
}
}
}
class CrimePoliceHolder(
val bindingCrimePolice: ListItemCrimePoliceBinding
) : Holder(bindingCrimePolice) {
override fun bind(crime: Crime) {
bindingCrimePolice.crimeTitle.text = crime.title
bindingCrimePolice.crimeDate.text = crime.date.toString()
bindingCrimePolice.root.setOnClickListener {
Toast.makeText(
bindingCrimePolice.root.context,
"${crime.title} clicked!",
Toast.LENGTH_SHORT
).show()
}
}
}
class CrimeListAdapter(
private val crimes: List<Crime>
) : RecyclerView.Adapter<Holder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
val inflater = LayoutInflater.from(parent.context)
if (viewType == 1) {
val binding = ListItemCrimeBinding.inflate(inflater, parent, false)
return CrimeHolder(binding)
} else {
val binding = ListItemCrimePoliceBinding.inflate(inflater, parent, false)
return CrimePoliceHolder(binding)
}
}
override fun getItemViewType(position: Int): Int {
return if (crimes[position].requirePolice) 1 else 0
}
override fun onBindViewHolder(holder: Holder, position: Int) {
val crime = crimes[position]
holder.bind(crime)
}
override fun getItemCount() = crimes.size
}
Thanks for your comments in advance!