Kotlin recyleview with viewholder

shivam kewat
2 min readJan 26, 2020

--

Lets create it then!

First create project with your desired name ofcourse

Create new layout for every item in list item_list.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:background="@color/colorAccent"
android:id="@+id/colorLayout"
android:layout_height="90dp">



</LinearLayout>

Configure our main layout activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">


<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyleView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>

Now we will create two classes one will extend RecylerView.Adapter and other one extend RecyclerView.ViewHolder

class MyAdapterViewHolder(view: View):RecyclerView.ViewHolder(view){
val colorLayout:LinearLayout = view.findViewById(R.id.colorLayout)
}

class Adapter(private val colorList:List<Int> ): RecyclerView.Adapter<MyAdapterViewHolder>(){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyAdapterViewHolder {

val view = LayoutInflater.from(parent.context).inflate(R.layout.ltem_list,parent,false)

return MyAdapterViewHolder(view)
}

override fun getItemCount(): Int {
return colorList.size
}

override fun onBindViewHolder(holder: MyAdapterViewHolder, position: Int) {

holder.colorLayout.setBackgroundColor(
ContextCompat.getColor(holder.colorLayout.context,colorList[position]))

}


}

As you can see our Adapter class will need a reference of our viewholder class for creating view for single time

Now wireup everything in activity_main.kt

val colorList = arrayListOf<Int>(
android.R.color.holo_blue_bright,
android.R.color.holo_orange_light,
android.R.color.holo_green_light,
android.R.color.holo_purple,
android.R.color.holo_red_light,
android.R.color.white,
android.R.color.holo_purple,
android.R.color.holo_green_light,
android.R.color.holo_orange_light
)

val adapter = Adapter(colorList)
recyleView.layoutManager = LinearLayoutManager(this)
recyleView.adapter = adapter

--

--

shivam kewat
shivam kewat

Written by shivam kewat

Hello there Devs! I like building apps for the worlds ...

No responses yet