Skip to content

Instantly share code, notes, and snippets.

@iniyan455
Last active September 3, 2020 18:20
Show Gist options
  • Save iniyan455/2f8a006a47682076eccb19c0765ff5e4 to your computer and use it in GitHub Desktop.
Save iniyan455/2f8a006a47682076eccb19c0765ff5e4 to your computer and use it in GitHub Desktop.
Live Template in android studio for common use case
File and code templates option in android studio to automate creation of recyclerview adapter.
AndroidStudio -> Preference->Editor->File and Code Template
Click plus icon at the top then you will see a panel with name, extension and code template editor. All you need to do is enter the template name, mention the extension(kt, java or xml) and paste the above template here and click OK. It’s done, all you need to do is just navigate to the package where you want to create the adapter and right click on it and select then you should see a file with name you mentioned while creating file template.
Feel free to comment if there any suggestions or improvements
#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
import kotlinx.android.extensions.LayoutContainer
class ${NAME} : RecyclerView.Adapter<${NAME}.${Model}Viewholder>() {
var data:List<${Model}> = emptyList()
set(newList) {
val calculateDiff = DiffUtil.calculateDiff(${Model}DiffCallback(field,newList))
calculateDiff.dispatchUpdatesTo(this)
field = newList
}
override fun getItemCount(): Int = data.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ${Model}Viewholder {
return ${Model}Viewholder(
LayoutInflater.from(parent.context)
.inflate(R.layout.${Layout}, parent, false)
)
}
override fun onBindViewHolder(holder: ${NAME}.${Model}Viewholder, position: Int) {
holder.bind(data[position])
}
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 old.id == new.id
}
override fun getOldListSize(): Int {
return oldList.size
}
override fun getNewListSize(): Int {
return newList.size
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment