Sobes.tech
Junior — Middle

How does RecyclerView handle the display of list items on the screen?

sobes.tech AI

Answer from AI

RecyclerView is responsible for displaying list items using the following key components:

  • LayoutManager — determines how the items are arranged on the screen (linear, grid, etc.).
  • Adapter — provides data and creates ViewHolders for each item.
  • ViewHolder — holds references to the View elements for reuse.

When scrolling, RecyclerView reuses ViewHolders to avoid creating new objects for each item, which significantly improves performance and reduces memory load.

Example of a simple Adapter:

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

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val textView = LayoutInflater.from(parent.context)
            .inflate(android.R.layout.simple_list_item_1, parent, false) as TextView
        return ViewHolder(textView)
    }

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

    override fun getItemCount() = items.size
}