How to use ViewBinding in a RecyclerView.Adapter?

前端 未结 7 2047
小鲜肉
小鲜肉 2021-02-05 01:59

Can I use ViewBindings to replace findViewById in this typical RecyclerView.Adapter initialization code? I can\'t set a binding val in the

相关标签:
7条回答
  • 2021-02-05 02:45

    Attach the binding to the ViewHolder instead of the View

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

    You pass the binding, the binding passes binding.root to RecyclerView.ViewHolder(binding.root)

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

    Then access anywhere with:

        holder.binding.title
    
    0 讨论(0)
提交回复
热议问题