Junior — Middle
Can you explain how RecyclerView works in Android?
sobes.tech AI
Answer from AI
RecyclerView is an Android component for displaying large lists or collections of data with high performance. Its key mechanism is recycling of list items, which reduces the costs of creating and rendering Views.
Main components of RecyclerView:
- Adapter: binds data to Views. Creates ViewHolders and fills them with data.
- ViewHolder: holds references to the View of a list item to avoid frequent calls to findViewById.
- LayoutManager: manages the layout of items on the screen (e.g., LinearLayoutManager for a vertical list).
Working mechanism:
- RecyclerView requests the Adapter to create ViewHolders for visible items.
- When an item scrolls out of the screen, its ViewHolder is placed in a pool for reuse.
- When a new item appears on the screen, RecyclerView takes a ViewHolder from the pool and updates its content via the Adapter.
This allows efficient memory usage and improves performance when working with large lists.
Example of a simple Adapter:
class MyAdapter(private val items: List<String>) : RecyclerView.Adapter<MyAdapter.MyViewHolder>() {
class MyViewHolder(val textView: TextView) : RecyclerView.ViewHolder(textView)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val textView = LayoutInflater.from(parent.context)
.inflate(android.R.layout.simple_list_item_1, parent, false) as TextView
return MyViewHolder(textView)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.textView.text = items[position]
}
override fun getItemCount() = items.size
}