Introduction
RecyclerView is a powerful tool for displaying large amounts of data in a user-friendly way. It is a part of the Android Jetpack library and is used to display large datasets in a list or grid format. It is an efficient way to display data and can be used with Kotlin to create a powerful and efficient user interface. In this article, we will discuss how to use RecyclerView in Kotlin. We will cover the basics of RecyclerView, how to set it up, and how to use it to display data. We will also discuss some of the best practices for using RecyclerView in Kotlin.
Solution
Below is a sample code to use RecyclerView in Kotlin:
// Create a RecyclerView
val recyclerView = RecyclerView(this)
// Set the layout manager
val layoutManager = LinearLayoutManager(this)
recyclerView.layoutManager = layoutManager
// Create an adapter
val adapter = MyAdapter(myDataSet)
recyclerView.adapter = adapter
// Add the RecyclerView to the layout
val parentLayout = findViewById
parentLayout.addView(recyclerView)
First You will need to create a layout for how a single row in your list will look(considering we are creating horizontal listing)
navigate to res > layout folder in your project, in layout folder create a Layout Resource File (fancy name, but it’s just a XML file)
for example:-
layout_demo_item.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp">
<ImageView
android:id="@+id/a_image"
android:layout_width="80dp"
android:layout_height="80dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/text_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="@+id/a_image"
app:layout_constraintStart_toEndOf="@+id/a_image"
app:layout_constraintTop_toTopOf="@+id/a_image" />
<TextView
android:id="@+id/text_random"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="@+id/text_title"
app:layout_constraintStart_toEndOf="@+id/text_title"
app:layout_constraintTop_toTopOf="@+id/text_title" />
</androidx.constraintlayout.widget.ConstraintLayout>
Second you need an Adapter.
An Adapter will take a list/array of data from you, render number of rows based on size of list and assign the data to each row based on position on list
for example:-
You have an array of 6 names, then the adapter will create 6 identical row based on layout_demo_item.xml
and assign data like 0th position data in array will be assigned to first element of list
MyAdapter.kt
class MyAdapter(var dataList: MutableList<DataModelObject>) : RecyclerView.Adapter<MyAdapter.MyViewHolder>() {
// inflating a layout in simple word is way of using a xml layout inside a class.
// if you look this is the same thing that your fragment doing inside onCreateView and storing that into "root" variable, we just did that in "view"
// we passed "view" to MyViewHolder and returned an object of MyViewHolder class(this object actually a single row without data)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.layout_demo_item, parent, false)
return MyViewHolder(view)
}
//the returned object of MyViewHolder class will come here and also with the position on which it gonna show,
// now based on this position we can get the value from our list and finally set it to the corresponding view that we have here in variable "holder"
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.textView.text = dataList.get(position).title
holder.textViewRandom.text = dataList.get(position).randomText
//hardcoding the image, just for simplicity, you can set this also from data list same as above
holder.aImage.setImageResource(R.mipmap.ic_launcher)
//here is the image setup by using glide
//Glide.with(holder.aImage.context).load(dataList.get(position).image).into(holder.aImage)
}
// this method telling adapter to how many total rows will be rendered based on count, so we returning the size of list that we passing
override fun getItemCount(): Int {
return dataList.size
}
// while creating the object in onCreateViewHolder, we received "view" here, and as you can see in your fragment,
// we can do find views by id on it same as we doing in fragment
// so your MyViewHolder now hold the reference of the actual views, on which you will set data
class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var textView: TextView
var textViewRandom: TextView
var aImage: ImageView
init {
textViewRandom = itemView.findViewById(R.id.text_random)
textView = itemView.findViewById(R.id.text_title)
aImage = itemView.findViewById(R.id.a_image)
}
}
}
here is the data class that we using as our model class(same as a POJO
class in Java
but it’s just in Kotlin
)
data class DataModelObject(var randomText:String,var title :String) {
}
We have all things set to create a recyclerView
, so now we will define recyclerView
in Fragment like
fragment_home.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/text_home"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:textAlignment="center"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view_home"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/text_home" />
</androidx.constraintlayout.widget.ConstraintLayout>
Finally Inside kotlin class setting up a recyclerView
HomeFragment.kt
(i’m not including the irrelevant methods and variable that you have in this fragment, please consider them)
class HomeFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val root = inflater.inflate(R.layout.fragment_home, container, false)
val textView: TextView = root.findViewById(R.id.text_home)
val recyclerView: RecyclerView = root.findViewById(R.id.recycler_view_home)
callAPIDemo(textView)
setUpRecyclerView(recyclerView);
return root
}
private fun setUpRecyclerView(recyclerView: RecyclerView) {
// first our data list that can come from API/Database
// for now i'm just manually creating the list in getDummyData()
val list: MutableList<DataModelObject> = getDummyData()
// created an adapter object by passing the list object
var myAdapter = MyAdapter(list)
//it's a layoutManager, that we use to tell recyclerview in which fashion we want to show list,
// default is vertical even if you don't pass it and just pass the activity , and we don't want to reversing it so false
// by customizing it you can create Grids,vertical and horizontal lists, even card swipe like tinder
val linearLayoutManager = LinearLayoutManager(activity,LinearLayoutManager.VERTICAL,false)
// just set the above layout manager on RecyclerView
recyclerView.layoutManager = linearLayoutManager
//and give it a adapter for data
recyclerView.adapter = myAdapter
}
private fun getDummyData(): MutableList<DataModelObject> {
val list: MutableList<DataModelObject> = mutableListOf(
DataModelObject("dfgdfg", "title 1"),
DataModelObject("tyuityui", "title 2"),
DataModelObject("yuti", "title 3"),
DataModelObject("uY9NOrc-=s180-rw", "title 4"),
DataModelObject("logo_color_272x92dp.png", "title 5"),
DataModelObject("NOVtP26EKH", "title 6"),
DataModelObject("googlelogo_color", "title 7"),
DataModelObject("sNOVtP26EKHePkwBg-PkuY9NOrc-", "title 8")
)
return list
}
}
12
solved How to use RecyclerView in kotlin
Solved: How to Use RecyclerView in Kotlin
RecyclerView is a powerful tool for displaying large amounts of data in a list format. It is a part of the Android Jetpack library and is a more advanced and flexible version of ListView. It is used to display large sets of data in a list format, and is often used in conjunction with other Android components such as ViewPager and CardView. In this article, we will discuss how to use RecyclerView in Kotlin.
Step 1: Add the Dependency
The first step is to add the RecyclerView dependency to your project. To do this, open your app’s build.gradle file and add the following line:
implementation 'androidx.recyclerview:recyclerview:1.1.0'
Step 2: Create the Layout
Next, create the layout for the RecyclerView. This layout will contain the RecyclerView and any other views you want to include. For example, you may want to include a TextView for displaying the title of the list, or a Button for adding new items to the list. Here is an example of a simple layout for a RecyclerView:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="My List" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Step 3: Create the Adapter
The next step is to create the adapter for the RecyclerView. The adapter is responsible for binding the data to the views in the list. To create the adapter, create a new class that extends RecyclerView.Adapter. Here is an example of a simple adapter for a RecyclerView:
class MyAdapter(private val items: List<String>) : RecyclerView.Adapter<MyAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_list, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.textView.text = items[position]
}
override fun getItemCount(): Int {
return items.size
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val textView: TextView = itemView.findViewById(R.id.text_view)
}
}
Step 4: Set the Adapter
The final step is to set the adapter for the RecyclerView. To do this, get a reference to the RecyclerView in your Activity or Fragment and set the adapter:
val recyclerView = findViewById<RecyclerView>(R.id.recycler_view)
val adapter = MyAdapter(items)
recyclerView.adapter = adapter
And that’s it! You have now successfully implemented a RecyclerView in Kotlin.