How to use ViewBinding in a RecyclerView.Adapter?

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

    You may use data binding like this.

    class CardListAdapter(
            private val mActivity: FragmentActivity?
        ) :
            RecyclerView.Adapter() {
             private var mCustomLayoutBinding: CustomLayoutBinding? = null
    
              inner class MyViewHolder(val mBinding: CustomLayoutBinding) :
                RecyclerView.ViewHolder(mBinding.getRoot())
         override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
                if (layoutInflater == null)
                    layoutInflater = LayoutInflater.from(parent.context)
    
                var viewHolder: RecyclerView.ViewHolder? = null
                val inflater = LayoutInflater.from(parent.context)
    
           viewHolder = getViewHolder(parent, inflater)
                     return viewHolder!!
                }
                private fun getViewHolder(
                parent: ViewGroup,
                inflater: LayoutInflater
            ): RecyclerView.ViewHolder {
                mCustomLayoutBinding =
                    DataBindingUtil.inflate(inflater, R.layout.custom_layout, parent, false)
                return MyViewHolder(this!!.mAssistanceLogCustomLayoutBinding!!)
            }
              override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
                val taskModal = mArrayList.get(position)
                 holder.mBinding.txtTitle.setText(taskModal.title)
                  }
                  override fun getItemCount(): Int {
                return assistanceArrayList.size
            }
    
            override fun getItemId(position: Int): Long {
                return position.toLong()
            }
    
            override fun getItemViewType(position: Int): Int {
                return position
            }
            }
    

提交回复
热议问题