Skip to content

Instantly share code, notes, and snippets.

@Schadenfeude
Last active August 20, 2020 16:22
Show Gist options
  • Save Schadenfeude/b1eb9e77421e1948d65a206eb8e60bc8 to your computer and use it in GitHub Desktop.
Save Schadenfeude/b1eb9e77421e1948d65a206eb8e60bc8 to your computer and use it in GitHub Desktop.
Live Template for RecyclerView Adapter with ListAdapter
#if (${PACKAGE_NAME} && ${PACKAGE_NAME} != "")package ${PACKAGE_NAME}#end
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.dronesense.pilotkit.common.extension.inflate
#parse("File Header.java")
internal class ${NAME}(private val onClick: (${Model_Class}) -> Unit) : ListAdapter<${Model_Class}, ${Class_Object_Name}ViewHolder>(${Class_Object_Name}ItemCallback) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ${Class_Object_Name}ViewHolder =
${Class_Object_Name}ViewHolder(parent.inflate(R.layout.${Layout_Name}), onClick)
override fun onBindViewHolder(holder: ${Class_Object_Name}ViewHolder, position: Int) = holder.bind(getItem(position))
}
internal class ${Class_Object_Name}ViewHolder(view: View, private val onClick: (${Model_Class}) -> Unit) : RecyclerView.ViewHolder(view) {
private val sampleView by lazy { view.findViewById<View>(R.id.sampleView) }
fun bind(item: ${Model_Class}) {
itemView.setOnClickListener { onClick.invoke(item) }
}
}
internal object ${Class_Object_Name}ItemCallback : DiffUtil.ItemCallback<${Model_Class}>() {
override fun areItemsTheSame(first: ${Model_Class}, second: ${Model_Class}): Boolean {
return first == second
}
override fun areContentsTheSame(first: ${Model_Class}, second: ${Model_Class}): Boolean {
return first == second
}
}
//This is what the parent.inflate() extension function does
fun ViewGroup.inflate(@LayoutRes layoutId: Int): View {
return LayoutInflater.from(context).inflate(layoutId, this, false)
}
@Schadenfeude
Copy link
Author

More info on how to set this up here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment