How to use ViewBinding in a RecyclerView.Adapter?

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

    I wrote a simple and reusable one:

    class ViewBindingVH private constructor(val binding: ViewBinding) :
        RecyclerView.ViewHolder(binding.root) {
        
        companion object {
            inline fun createVH(
                parent: ViewGroup,
                crossinline block: (inflater: LayoutInflater, container: ViewGroup, attach: Boolean) -> ViewBinding
            ) = ViewBindingVH(block(LayoutInflater.from(parent.context), parent, false))
        }
    }
    
    
    class CardAdapter : RecyclerView.Adapter() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewBindingVH {
            return ViewBindingVH.createVH(parent, CardBinding::inflate)
        }
    
        override fun onBindViewHolder(holder: ViewBindingVH, position: Int) {
            (holder.binding as CardBinding).apply {
                //bind model to view
                title.text = "some text"
                descripiton.text = "some text"
            }
        }
    
    }
    

提交回复
热议问题