My name is Gabriel Levindo, I live in Saquarema, Rio de Janeiro, I’m 24 years old, and I have a degree in Information Systems from Estácio de Sá University. With 2 years of experience in Android development, I am an expert in the field and always strive to expand my knowledge. Recently, I faced the challenge of implementing a list screen using RecyclerView, which is essential for anyone working with Android. Although I already had experience in app development, RecyclerView required in-depth study, which allowed me to further solidify my expertise.
But what is a RecyclerView?
Below, we have a task list that allows you to add, update, and delete tasks in a simple way, with several elements.
Let's implement it together?
Initially, I found myself lost with which components to use and had to redo it at least four times to get a grasp of its functionalities. For this reason, I’m writing this article to not only solidify my knowledge but also to help others who may be struggling to better understand RecyclerView. If you like my article, share it to help others as well.
In this article, I’ll explain the implementation of RecyclerView, and by the end of this reading, you'll understand:
• RecyclerView UI;
• RecyclerView Adapter;
• ViewHolder;
• LayoutManager.
RecyclerView: The RecyclerView is a class in Android that enables displaying large datasets in a scrollable list or grid, optimizing performance and memory efficiency. It is an evolution of ListView and GridView, offering more flexibility and customization options. Moreover, it consists of three main components: ViewHolder, Adapter, and LayoutManager.
ViewHolder: The ViewHolder is responsible for creating and managing individual list item views, setting and maintaining references to the visual elements of a list item for dynamic updates. It provides a reference to the view that can be reused, reducing findViewById calls, thus improving performance.
Adapter: The Adapter supplies data to the RecyclerView, creates ViewHolders for each list item, and binds data to those ViewHolders. It acts as a bridge between the data source and the views that display the data.
LayoutManager: The LayoutManager organizes the list items, determining how each item is displayed and positioned on the screen. RecyclerView provides built-in LayoutManagers such as LinearLayoutManager, GridLayoutManager, and StaggeredGridLayoutManager, each offering different arrangements and behaviors for list items.
RecyclerView supports animations for item additions, removals, and movements (gestures). It is highly customizable, allowing personalized item layouts for each element in the list. RecyclerView is optimal for displaying large datasets in a scrollable list, providing superior efficiency and performance compared to ListView. To implement RecyclerView, an XML layout file must be included in the res/layout directory.
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rv_task_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
tools:listitem="@layout/item_task" />
In this way, we can initialize our RecyclerView, and from there, we need to implement our Adapter. To create the adapter, there are three primary methods we need to override: onCreateViewHolder, onBindViewHolder, and getItemCount.
onCreateViewHolder: The primary responsibility of this method is to inflate the item layout and instantiate a new ViewHolder to hold references to the item views. RecyclerView invokes this method when it needs to create a new ViewHolder to display a list item.
onBindViewHolder: This method's main responsibility is to bind data to the ViewHolder by updating its UI elements. RecyclerView calls this method when it needs to update an existing ViewHolder with fresh data.
getItemCount: This method returns the total number of items to be displayed by the RecyclerView. It is crucial for RecyclerView to know how many items to render, allowing it to properly manage its layout and scrolling behavior. In essence, getItemCount informs the RecyclerView about the dataset size it is working with.
Additionally, we utilize the bind function within the Adapter to update the display of a specific item based on the provided data. Typically, it is implemented in the Adapter class and receives a data object representing the view's content. For instance, in a contact list, the bind method would update the text fields or the associated data models for each item view.
To implement the Adapter, we need to create a custom class that extends RecyclerView.Adapter and override the aforementioned methods as follows:
//Here we create the Adapter, passing the RecyclerView.
class TaskListAdapter(
private val openTaskDetailView:(task:Task) -> Unit
) :
ListAdapter<Task,TaskListViewHolder>(TaskListAdapter){
private var listTask: List<Task> = emptyList()
//would be the OnCreateViewHolder.
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TaskListViewHolder {
val view: View = LayoutInflater
.from(parent.context)
.inflate(R.layout.item_task, parent, false)
return TaskListViewHolder(view)
}
//would be the onBindViewHolder.
override fun onBindViewHolder(holder: TaskListViewHolder, position: Int) {
val task = getItem(position)
holder.bind(task, openTaskDetailView)
}
}
}
//would be the ViewHolder at adapter.
class TaskListViewHolder(private val view: View) : RecyclerView.ViewHolder(view) {
private val tvTaskTitle = view.findViewById<TextView>(R.id.tv_task_title)
private val tvTaskDescription = view.findViewById<TextView>(R.id.tv_task_description)
//Aqui seria o Bind do adaptador
fun bind(task: Task, openTaskDetailView:(task:Task) -> Unit) {
tvTaskTitle.text = task.title
tvTaskDescription.text = task.description
}
}
}
Advantages of using RecyclerView:
Performance Efficiency: RecyclerView is optimized to handle large datasets, making it more memory-efficient and performant in comparison to traditional list-based components like ListView. It reuses views through ViewHolder to minimize the overhead of view inflation, reducing memory consumption and improving scrolling performance.
Flexibility: RecyclerView provides great flexibility, enabling developers to customize the appearance and behavior of the list according to specific requirements. You can modify item arrangements, animations, and data binding, offering a highly adaptable solution.
Support for Different Layout Types: RecyclerView supports various layout types, such as LinearLayoutManager, GridLayoutManager, and StaggeredGridLayoutManager, allowing the creation of both horizontal and vertical lists, grids, and complex item arrangements, providing a versatile UI design for the user interface.
Animation Features: RecyclerView includes built-in support for animations, such as adding, removing, or moving items within the list with smooth transitions. These animations enhance the user experience by making list updates feel more fluid and visually engaging.
With RecyclerView and its various implementations, you can significantly improve your app's performance and achieve greater customization flexibility. It is ideal for displaying lists and large datasets. It also supports multiple layout types and animation features, ensuring the best possible user experience. In summary, RecyclerView is a vital tool for Android developers looking to create efficient and customizable user interfaces.
Link at documentation of RecyclerView:
https://developer.android.com/guide/topics/ui/layout/recyclerview?hl=pt-br
Top comments (4)
Ficou show demais!
Ficou muito boa sua explicação
Muito bom artigo Gabriel! parabéns pela iniciativa, esse tipo de artigo nos ajuda a entender de uma forma mais simples como funciona o RecyclerView! estou ansioso para ver os seus próximos artigos.
Ótima explicação!!