Sobes.tech
Junior — Middle

What functions need to be overridden in the Adapter class for correct operation with RecyclerView?

sobes.tech AI

Answer from AI

To ensure the correct operation of the adapter with RecyclerView, the following methods need to be overridden:

  1. onCreateViewHolder(ViewGroup parent, int viewType) — creates a new ViewHolder, initializing the layout of the list item.
  2. onBindViewHolder(ViewHolder holder, int position) — binds data to the list item, updating the ViewHolder's content.
  3. getItemCount() — returns the number of items in the adapter.

Example in Kotlin:

class MyAdapter(private val items: List<String>) : RecyclerView.Adapter<MyAdapter.MyViewHolder>() {

    class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val textView: TextView = itemView.findViewById(R.id.textView)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_layout, parent, false)
        return MyViewHolder(view)
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        holder.textView.text = items[position]
    }

    override fun getItemCount(): Int = items.size
}