Challenge: RecyclerView View Types

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!

1 Like

Hey, did you ever figure this out with ViewBinding? I’m having trouble returning a different ViewHolder in onCreateViewHolder. Everything else wasnt a problem, creating a separate xml file, adding the extra value to the data class and then overriding getItemViewType all were relatively straight forward. I just cant figure out how to return the second layout file that I created because everything is bound to the original layout file that the book has you create using CrimeHolder.