web-dev-qa-db-ja.com

RecyclerView.AdapterでViewBindingを使用する方法

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

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

私はシンプルで再利用可能なものを書きました:

class ViewBindingVH private constructor(val binding: ViewBinding) :
    RecyclerView.ViewHolder(binding.root) {

    companion object {

        fun createVH(
            parent: ViewGroup,
            block: (inflater: LayoutInflater, container: ViewGroup, attach: Boolean) -> ViewBinding
        ) = ViewBindingVH(block(LayoutInflater.from(parent.context), parent, false))
    }
}


class CardAdapter : RecyclerView.Adapter<ViewBindingVH>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewBindingVH {
        return ViewBindingVH.createVH(parent, CardBinding::inflate)
    }

    override fun onBindViewHolder(holder: ViewBindingVH, position: Int) {
        val binding = holder.binding as CardBinding
    }

}
0
Alan W