1 sec to write a RecyclerViewAdapter

By August 9, 2019 February 24th, 2020 4 Comments

My job consists in making quality Apps in a reasonable short time.

When I notice there is something that takes time to be done and I do it frequently. Then, I try to optimize it.

Creating a RecycleViewAdapter with its classes DiffCalculation, ViewHolder takes me some time.

Therefore, I create a template for AndroidStudio that takes 3 values, name of the Adapter, name of the Model that uses the Adapter, and the resource layout. Give it a try!

#if (${PACKAGE_NAME} && ${PACKAGE_NAME} != "")package ${PACKAGE_NAME}#end

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView

class ${NAME} : RecyclerView.Adapter<${NAME}.${Model}Viewholder>()  {

    var data:List<${Model}> = emptyList()
        set(newList) {
            val calculateDiff = DiffUtil.calculateDiff(${Model}DiffCallback(field,newList))
            field = newList

    override fun getItemCount(): Int = data.size
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ${Model}Viewholder {
        return ${Model}Viewholder(
                        .inflate(R.layout.${Layout}, parent, false)

    override fun onBindViewHolder(holder: ${NAME}.${Model}Viewholder, position: Int) {

    inner class ${Model}Viewholder(override val containerView: View) : RecyclerView.ViewHolder(containerView),
        LayoutContainer {
         fun bind(item: ${Model}) = with(itemView) {

class ${Model}DiffCallback(val oldList:List<${Model}>,val newList:List<${Model}>) : DiffUtil.Callback() {
    override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
        return oldList[oldItemPosition].id == newList[newItemPosition].id

    override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
        val old = oldList[oldItemPosition]
        val new = newList[newItemPosition]

        return ==


    override fun getOldListSize(): Int {
        return oldList.size

    override fun getNewListSize(): Int {
        return newList.size

How to include it in Android Studio

You can add the template easily. First copy the code above. Then click on AndroidStudio -> Preference->Editor->File and Code Template

Click on “+” to add a new template. Name as you want and be careful to put “kt” as Extension. Finally just paste the code in the text box and you are done!

Animation include template
How include the template


How really use this? Just “right clickon the package folder you want to create the class. Select “new“, you should see in the list the name of your template along with other templates. Voilà!

Usage of the template

I hope you find this useful! Do you use any other ways to speed up your repeated work? Let’s discuss it!


Author Ernie

More posts by Ernie

Join the discussion 4 Comments