How to use ViewBinding in a RecyclerView.Adapter?

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

    You may use view-binding like this :

    package com.example.kotlinprogramming.adapter
    
    import android.content.Context
    import android.view.LayoutInflater
    import android.view.ViewGroup
    import androidx.recyclerview.widget.RecyclerView
    import com.example.kotlinprogramming.data.HobbiesData
    import com.example.kotlinprogramming.databinding.ItemHobbieBinding
    
    class HobbiesAdapter(var context: Context, var hobbiesList: List) :
    RecyclerView.Adapter() {
    
    
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HobbiesViewHolder {
        val view = ItemHobbieBinding.inflate(LayoutInflater.from(context) , parent,false)
        return HobbiesViewHolder(view)
    }
    
    override fun onBindViewHolder(holder: HobbiesViewHolder, position: Int) {
        val hobbie = hobbiesList.get(position)
        holder.viewBinding.tvHobbie.text = hobbie.title
    }
    
    inner class HobbiesViewHolder(var viewBinding: ItemHobbieBinding) : RecyclerView.ViewHolder(viewBinding.root) {
    }
    
    override fun getItemCount(): Int {
        return hobbiesList.size
    }
    
    }
    

    Here is item_hobbies.xml

    
    
    
    
    

提交回复
热议问题