RecyclerView and Adapters. Creating RecyclerView. Using Custom Adapter and ViewHolder class
What is RecyclerView?
How RecyclerView Works�RecyclerView operates through three main components:
Component | Function |
RecyclerView | The main container where data items are displayed. |
Adapter | Binds the data to the individual views (items) in the RecyclerView. |
ViewHolder | Holds the references to the item’s views for efficient reuse. |
The term “Recycle” means that RecyclerView reuses the views that have scrolled off-screen instead of creating new ones, improving performance and reducing memory use.
Steps to Create a RecyclerView� Step 1: Add RecyclerView to your layout
<androidx.recyclerview.widget.RecyclerView android:id="@+id/recyclerView" android:layout_width="match_parent" android:layout_height="match_parent" �android:padding="8dp"/>
Step 2: Create a model class�You need a model class to represent the data to be displayed.
public class Student {
String name;
int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
}
Step 3: Create a Custom Adapter�The Adapter connects your data with the RecyclerView items using a ViewHolder.
public class StudentAdapter extends RecyclerView.Adapter<StudentAdapter.StudentViewHolder> {
private List<Student> studentList;
public StudentAdapter(List<Student> studentList) {
this.studentList = studentList;
}
static class StudentViewHolder extends RecyclerView.ViewHolder {
public StudentViewHolder(@NonNull View itemView) {
super(itemView);
}
}
�
4. About the ViewHolder Class
For example:
Type | Description |
Default Adapter | Uses predefined data structures like ArrayAdapter or SimpleAdapter. |
Custom Adapter | Designed by the developer for custom layouts, models, and logic. Provides full flexibility. |
Difference Between Adapter and Custom Adapter
With a Custom Adapter, you can include Buttons, ImageViews, Switches, SeekBars, and attach onClick listeners for each item.
4-bosqich: Item layout fayl yaratish (item_student.xml)�5-bosqich: MainActivity’da RecyclerView’ni sozlash
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
studentList = new ArrayList<>();
studentList.add(new Student("Ali", 20));
studentList.add(new Student("Laylo", 22));
studentList.add(new Student("Javohir", 19));
adapter = new StudentAdapter(studentList);
recyclerView.setAdapter(adapter);
Types of LayoutManager
RecyclerView uses LayoutManager to define how items are arranged:
LayoutManager | Description |
LinearLayoutManager | Displays items vertically or horizontally (like a list). |
GridLayoutManager | Displays items in a grid layout (like a table). |
StaggeredGridLayoutManager | Displays items in uneven grid style (like Pinterest). |