Junior — Middle
Explain the mechanism of RecyclerView in the context of using XML resources for list display.
sobes.tech AI
Answer from AI
RecyclerView is an Android component for efficiently displaying large lists or grids of items. It uses XML resources to define the appearance of each list item.
Working mechanism:
- LayoutManager manages the positioning of items.
- Adapter binds data to interface elements. In the adapter, the
onCreateViewHoldermethod inflates the XML layout of a list item — that is, creates a View from XML. - ViewHolder holds references to Views within the item for reuse.
- RecyclerView reuses ViewHolders to avoid creating new Views for each item, which improves performance.
Example of item view XML layout (item_view.xml):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp" />
</LinearLayout>
In the adapter:
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_view, parent, false)
return ViewHolder(view)
}
Thus, XML resources define the appearance of elements, and RecyclerView efficiently manages their creation and reuse.