[Solved] How to use RecyclerView in kotlin


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