How to use ViewBinding in a RecyclerView.Adapter?

前端 未结 7 2042
小鲜肉
小鲜肉 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
    

提交回复
热议问题