Here is the code I used in my RecycleView
adapter class. I don\'t know this is the right way or not to use View Binding. If you have a better solution answer me. Th
For the folks looking for a solution in Kotlin, here it is:
It's a minimal example, where the adapter gets an array of Strings and displays each of the them in a layout called recyclerview_item
in a TextView called itemTextView
.
It's based on @SomeshKumar's answer and answers @Vijay Villiers question on how to get rid of the private TextView txt;
Edit: New Version: I noticed the generated ...Binding has a .bind() function, so let's use it. (I guess it might be less resource-heavy?)
class SampleAdapter(private val context: Context, private val content: Array) :
RecyclerView.Adapter()
{
class CustomViewHolder(view: View) : RecyclerView.ViewHolder(view)
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int) =
CustomViewHolder(
// Alternatively inflate like usual, if you don't need binding
RecyclerviewItemBinding
.inflate(LayoutInflater.from(context), viewGroup, false)
.root
)
override fun getItemCount() = content.size
override fun onBindViewHolder(viewHolder: CustomViewHolder, position: Int)
{
RecyclerviewItemBinding.bind(viewHolder.itemView).apply{
itemTextView.text = content[position]
}
}
}
Edit: Old Version:
class SampleAdapter(private val context: Context, private val content: Array) :
RecyclerView.Adapter()
{
class CustomViewHolder(var viewBinding: RecyclerviewItemBinding) :
RecyclerView.ViewHolder(viewBinding.root)
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int) =
CustomViewHolder(
RecyclerviewItemBinding
.inflate(LayoutInflater.from(context), viewGroup, false)
)
override fun getItemCount() = content.size
override fun onBindViewHolder(viewHolder: CustomViewHolder, position: Int)
{
viewHolder.viewBinding.apply {
itemTextView.text = content[position]
}
}
}