RecyclerViewis a view group that's used to efficiently display large sets of data by recycling views as they scroll off the screen.
- It's an advanced version of
ListViewandGridView, offering better performance and more customizable features.
Here's a breakdown of its key components and functionalities:
Adapter:
- The
RecyclerViewrequires an adapter that manages the data and creates views for individual items. This adapter extendsRecyclerView.Adapterand overrides methods like onCreateViewHolder(to create new views),-
onBindViewHolder(to bind data to views), - and
getItemCount(to determine the number of items).
LayoutManager:
RecyclerViewuses aLayoutManagerto position items within the view. There are different layout managers available such asLinearLayoutManager,GridLayoutManagerStaggeredGridLayoutManager.
// inside fragment use context binding.homeRecycleView.layoutManager = LinearLayoutManager(context) // inside activity use this@ActivityName // context , orientation , isReversed binding.homeRecycleView.layoutManager = LinearLayoutManager(this@YourActivity,LinearLayoutManager.HORIZONTAL,false)
// contex and spanCount( Column Count ) binding.homeRecycleView.layoutManager = GridLayoutManager(context,2) // context , spanCount , Orientation , isReversedList binding.homeRecycleView.layoutManager = GridLayoutManager(this@YourActivity,2,GridLayoutManager.VERTICAL,false)
binding.homeRecycleView.layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
They control how items are arranged, scrolled, and recycled.
ViewHolder:
- The
ViewHolderpattern is used to cache views of individual items. It helps in recycling the views that are no longer visible on the screen, making scrolling smoother and more efficient.
Item Decoration:
ItemDecorationallows customization of individual item views by adding decorations such as spacing, dividers, or decorators between items.- ItemAnimator:
It provides animations for adding, removing, and updating items within the
RecyclerView. - Click Listeners: To handle user interactions like item clicks or long presses, you can set click listeners within the adapter.
- Data Set Changes:
The adapter can notify the
RecyclerViewof any changes in the underlying dataset. Methods likenotifyItemInserted,notifyItemRemoved, etc., help in reflecting changes in the UI.
The workflow generally involves:
- Defining a layout for individual items in a separate XML file.
- Creating an adapter by extending
RecyclerView.Adapterand implementing required methods.
- Setting up the
RecyclerViewin your activity or fragment, specifying the adapter, layout manager, and any other configurations.
- Populating the
RecyclerViewwith data by setting the adapter and handling interactions.
- The
RecyclerViewis highly customizable and efficient for handling large data sets, making it a preferred choice for displaying lists or grids in Android applications. Its ability to recycle views efficiently helps in achieving smooth scrolling and improved performance, especially when dealing with extensive data.
Programmatically Set Attributes in Kotlin:
recyclerView.layoutManager:- Sets the layout manager programmatically. For example:
LinearLayoutManager,GridLayoutManagerStaggeredGridLayoutManager.
// inside fragment use context binding.homeRecycleView.layoutManager = LinearLayoutManager(context) // inside activity use this@ActivityName // context , orientation , isReversed binding.homeRecycleView.layoutManager = LinearLayoutManager(this@YourActivity,LinearLayoutManager.HORIZONTAL,false)
// contex and spanCount( Column Count ) binding.homeRecycleView.layoutManager = GridLayoutManager(context,2) // context , spanCount , Orientation , isReversedList binding.homeRecycleView.layoutManager = GridLayoutManager(this@YourActivity,2,GridLayoutManager.VERTICAL,false)
binding.homeRecycleView.layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
recyclerView.adapter:- Sets the adapter for the
RecyclerView. For example:
val adapter = CustomAdapter(this@MainActivity , items) recyclerView.adapter = adapter
- Other properties:
- You can also modify other properties programmatically, such as padding, item decorations, animations, and click listeners:
onCreateViewHolder:- Inflates the layout for individual items and initializes the
ViewHolder. onBindViewHolder:- Binds data to the views within the
ViewHolder. getItemCount:- Specifies the total number of items in the
RecyclerView. Myclass:- Contains references to views within the item layout, allowing for efficient recycling and manipulation.
recyclerview_item.xmldefines the layout for individual items in the list.- In
MainActivity.kt, theRecyclerViewand its layout manager are initialized. - A list of items is created (
items), and a custom adapter (CustomAdapter) is created and attached to theRecyclerView. - The adapter inflates the
recyclerview_item.xmllayout for each item and binds data to theTextViewinside it. - Put some statement to performed on click of button on item
holder.submit.setOnClickListener {...} - here submit is instance of button that connected with id of that view
- Performed some action on click of whole one item of list
- here itemView refers to the item that has been clicked and action to be performed based on that
recyclerView.addItemDecoration(DividerItemDecoration(this, LinearLayoutManager.VERTICAL)) recyclerView.itemAnimator = DefaultItemAnimator()
Adapter and ViewHolder:
When creating a custom adapter, attributes and methods within the adapter and its
ViewHolder here it is Myclass that is inherited by RecyclerView.ViewHolder() to work as viewHolder for the adapter , here are some significant:Customization:
Customize the
RecyclerView behavior and appearance through various methods and attributes based on your requirements, such as animations, decorations, click listeners, and more.These attributes and methods offer control over how the
RecyclerView displays and manages the list of items in your Android application. Each attribute provides a way to customize the behavior and appearance of the RecyclerView and its associated components.Kotlin Code (MainActivity.kt):
This Kotlin code sets up the
RecyclerView with an adapter to display a list of items.import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val recyclerView: RecyclerView = findViewById(R.id.recyclerView) recyclerView.layoutManager = LinearLayoutManager(this) val items = listOf("Item 1", "Item 2", "Item 3", "Item 4", "Item 5") val adapter = CustomAdapter(items) recyclerView.adapter = adapter } }
MyRecAdapter.kt
// extends to RecyclerView adapter with our class that resides in our main Adapter class class MyRecAdapter(var mainActivity: MainActivity, var userList: ArrayList<User>) : RecyclerView.Adapter<MyRecAdapter.Myclass>() { // Class holds the View that has to be craated class Myclass(itemView: View) : RecyclerView.ViewHolder(itemView) { var name : TextView var username : TextView var email : TextView var submit : Button // our view's objects connect in init block with id in view layout init { name = itemView.findViewById(R.id.name) username = itemView.findViewById(R.id.username) email = itemView.findViewById(R.id.email) submit = itemView.findViewById(R.id.submit) } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Myclass { var view = LayoutInflater.from(mainActivity).inflate(R.layout.myitem, parent, false) return Myclass(view) } override fun getItemCount(): Int = userList.size override fun onBindViewHolder(holder: Myclass, position: Int) { holder.name.text = userList[position].name holder.username.text = userList[position].username holder.email.text = userList[position].email // to perform some action on click of button resides in item holder.submit.setOnClickListener // action to be perfomed on click } // if you want to click on whole item view than holder.itemView.setOnClickListener { // action to be performed on click on whole item } } }
Explanation:
holder.itemView.setOnClickListener {...}