How to use ViewBinding in a RecyclerView.Adapter?

前端 未结 7 2059
小鲜肉
小鲜肉 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:30

    What you need to do is pass the generated binding class object to the holder class constructor. In below example, I have row_payment XML file for RecyclerView item and the generated class is RowPaymentBinding so like this

        class PaymentAdapter(private val paymentList: List) : RecyclerView.Adapter() {
            override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PaymentHolder {
                val itemBinding = RowPaymentBinding.inflate(LayoutInflater.from(parent.context), parent, false)
                return PaymentHolder(itemBinding)
            }
        
            override fun onBindViewHolder(holder: PaymentHolder, position: Int) {
                val paymentBean: PaymentBean = paymentList[position]
                holder.bind(paymentBean)
            }
        
            override fun getItemCount(): Int = paymentList.size
        
            class PaymentHolder(private val itemBinding: RowPaymentBinding) : RecyclerView.ViewHolder(itemBinding.root) {
                fun bind(paymentBean: PaymentBean) {
                    itemBinding.tvPaymentInvoiceNumber.text = paymentBean.invoiceNumber
                    itemBinding.tvPaymentAmount.text = paymentBean.totalAmount
                }
            }
        }
    

    Also, make sure you pass the root view to the parent class of Viewholder like this RecyclerView.ViewHolder(itemBinding.root) by accessing the passed binding class object.

提交回复
热议问题