Created
August 15, 2019 09:59
-
-
Save sergiandreplace/80dbeac2123a1543ac2a1c99de83399e to your computer and use it in GitHub Desktop.
AS File extension for RecyclerView adapters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#set($ModelName = $Model.replace("ViewModel","")) | |
#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<${ModelName}ViewHolder>() { | |
var data:List<${Model}> = emptyList() | |
set(newList) { | |
DiffUtil.calculateDiff(${Model}DiffCallback(field,newList)).dispatchUpdatesTo(this) | |
field = newList | |
} | |
override fun getItemCount(): Int = data.size | |
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ${ModelName}ViewHolder.build(parent) | |
override fun onBindViewHolder(holder: ${ModelName}ViewHolder, position: Int) { | |
holder.bind(data[position]) | |
} | |
inner class ${Model}DiffCallback(val oldList:List<${Model}>,val newList:List<${Model}>) : DiffUtil.Callback() { | |
override fun areItemsTheSame(oldPosition: Int, newPosition: Int) = oldList[oldPosition].id == newList[newPosition].id | |
override fun areContentsTheSame(oldPosition: Int, newPosition: Int) = oldList[oldPosition].id == newList[newPosition].id | |
override fun getOldListSize() = oldList.size | |
override fun getNewListSize() = newList.size | |
} | |
} | |
class ${ModelName}ViewHolder(val view: View) : RecyclerView.ViewHolder(view) { | |
fun bind(item: ${Model}) { | |
TODO("Write your code here") | |
} | |
companion object { | |
fun build(parent: ViewGroup) = ${ModelName}ViewHolder( | |
LayoutInflater.from(parent.context).inflate(R.layout.${Layout}, parent, false) | |
) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment