How to use ViewBinding in a RecyclerView.Adapter?

A1m :

Can I use ViewBindings to replace findViewById in this typical RecyclerView.Adapter initialization code? I can't set a binding val in the object as the ViewHolders are different per cell.

class CardListAdapter(private val cards: LiveData<List<Card>>) : RecyclerView.Adapter<CardListAdapter.CardViewHolder>() {

    class CardViewHolder(val cardView: View) : RecyclerView.ViewHolder(cardView)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CardViewHolder {
        val binding = CardBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return CardViewHolder(binding.root)
    }

    override fun onBindViewHolder(holder: CardViewHolder, position: Int) {
        val title = holder.cardView.findViewById<TextView>(R.id.title)
        val description = holder.cardView.findViewById<TextView>(R.id.description)
        val value = holder.cardView.findViewById<TextView>(R.id.value)
        // ...
    }
A1m :

I found two options:

Use the bind method on the Binding class

override fun onBindViewHolder(holder: CardViewHolder, position: Int) {
        val binding = CardBinding.bind(holder.cardView)
        // binding.title ...

Or attach the binding to the ViewHolder instead of the View

    class CardViewHolder(val binding: CardBinding) : RecyclerView.ViewHolder(binding.root)

Then access with:

    holder.binding.title

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=33085&siteId=1