Skip to content

Instantly share code, notes, and snippets.

@mitchtabian
Last active August 7, 2021 15:27
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save mitchtabian/e194485eee68a7846feb27f1ce1067b3 to your computer and use it in GitHub Desktop.
Save mitchtabian/e194485eee68a7846feb27f1ce1067b3 to your computer and use it in GitHub Desktop.
#if (${PACKAGE_NAME} && ${PACKAGE_NAME} != "")package ${PACKAGE_NAME}#end
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.AsyncListDiffer
import androidx.recyclerview.widget.DiffUtil
#parse("File Header.java")
class ${NAME}(private val interaction: Interaction? = null) :
RecyclerView.Adapter<RecyclerView.ViewHolder>(){
val DIFF_CALLBACK = object: DiffUtil.ItemCallback<${Model_Class}>(){
override fun areItemsTheSame(oldItem: ${Model_Class}, newItem: ${Model_Class}): Boolean {
TODO("not implemented")
}
override fun areContentsTheSame(oldItem: ${Model_Class}, newItem: ${Model_Class}): Boolean {
TODO("not implemented")
}
}
private val differ = AsyncListDiffer(this, DIFF_CALLBACK)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return ${ViewHolder_Class}(
LayoutInflater.from(parent.context).inflate(
R.layout.${Item_Layout_ID},
parent,
false
),
interaction
)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when(holder){
is ${ViewHolder_Class} -> {
holder.bind(differ.currentList.get(position))
}
}
}
override fun getItemCount(): Int {
return differ.currentList.size
}
fun submitList(list: List<${Model_Class}>){
differ.submitList(list)
}
class ${ViewHolder_Class}
constructor(
itemView: View,
private val interaction: Interaction?
) : RecyclerView.ViewHolder(itemView){
fun bind(item: ${Model_Class}) = with(itemView) {
itemView.setOnClickListener {
interaction?.onItemSelected(adapterPosition, item)
}
TODO("bind view with data")
}
}
interface Interaction {
fun onItemSelected(position: Int, item: ${Model_Class})
}
}
@BRUHItsABunny
Copy link

Line 72 should change from:
fun onItemSelected(position: Int, item: BlogPost)
To
fun onItemSelected(position: Int, item: ${Model_Class})

@mitchtabian
Copy link
Author

Thank you

@JuanFcoMiranda
Copy link

I would define the Interaction class as generic, like this:

interface Interaction<T> {
    fun onItemSelected(position: Int, item: T)
}

This way, you can define the interface only once and use it wherever you want.

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