Skip to content

Instantly share code, notes, and snippets.

@malwinder-s
Last active June 5, 2020 15:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save malwinder-s/9613922417c207b7d47b76c178a6bd6b to your computer and use it in GitHub Desktop.
Save malwinder-s/9613922417c207b7d47b76c178a6bd6b to your computer and use it in GitHub Desktop.
Generic Recycler View Adapter
package com.malwinder.kotlindemo.recyclerview
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
class Adapter<T>(
@LayoutRes private val layoutId: Int,
private val setData: (position: Int, dataItem: T, itemView: View) -> Unit
) :
ListAdapter<T, Adapter<T>.ViewHolder<T>>(object : DiffUtil.ItemCallback<T>() {
override fun areItemsTheSame(oldItem: T, newItem: T) =
oldItem.hashCode() == newItem.hashCode()
override fun areContentsTheSame(oldItem: T, newItem: T) = areItemsTheSame(oldItem, newItem)
}) {
inner class ViewHolder<T>(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun setData(position: Int) {
setData(position, getItem(position), itemView)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
ViewHolder<T>(LayoutInflater.from(parent.context).inflate(layoutId, parent, false))
override fun onBindViewHolder(holder: ViewHolder<T>, position: Int) = holder.setData(position)
}
/**
* Shows data on [RecyclerView] by setting adapter
*/
inline fun <reified T> RecyclerView.showData(
dataList: List<T?>? = null,
@LayoutRes layoutId: Int,
noinline setData: (position: Int, dataItem: T, itemView: View) -> Unit
) {
layoutManager = LinearLayoutManager(context)
adapter = Adapter(layoutId, setData).apply {
submitList(dataList)
}
}
/**
* Used for updating data to already added Adapter
*/
inline fun <reified T> RecyclerView.updateData(
dataList: List<T?>? = null
) {
@Suppress("UNCHECKED_CAST")
(adapter as Adapter<T>).submitList(dataList)
}
/**
* Refresh the data by calling notifyDataSetChanged
*/
fun RecyclerView.refresh() {
(adapter as Adapter<*>).notifyDataSetChanged()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment