RecyclerView.Adapter で ViewBinding を使用するにはどうすればいいですか? 質問する

RecyclerView.Adapter で ViewBinding を使用するにはどうすればいいですか? 質問する

findViewByIdこの一般的な初期化コードを置き換えるために ViewBindings を使用できますか? ViewHolders はセルごとに異なるため、オブジェクトに valRecyclerView.Adapterを設定することはできません。binding

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)
        // ...
    }

ベストアンサー1

必要なのは、生成されたバインディングクラスオブジェクトをホルダークラスのコンストラクタに渡すことです。以下の例では、アイテムrow_paymentのXMLファイルがありRecyclerView、生成されたクラスはRowPaymentBinding次のようになります。

class PaymentAdapter(private val paymentList: List<PaymentBean>) : RecyclerView.Adapter<PaymentAdapter.PaymentHolder>() {
    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
        }
    }
}

RecyclerView.ViewHolder(itemBinding.root)また、渡されたバインディング クラス オブジェクトにアクセスして、ルート ビューを Viewholder の親クラスに渡すようにしてください。

おすすめ記事