Skip to content

Instantly share code, notes, and snippets.

@brh
Created January 26, 2021 20:45
Show Gist options
  • Save brh/a69f2ff9dbcb89a05da6c0ab2d7414fb to your computer and use it in GitHub Desktop.
Save brh/a69f2ff9dbcb89a05da6c0ab2d7414fb to your computer and use it in GitHub Desktop.
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
/**
* A generic RecyclerView Adapter that is useful for quick spin up..
* This removes the need of having to define a bunch of ViewHolders or repeated Adapter classes, by delegating the work to the
* CustomViewAdapterConfig where you can define you View Types [CustomViewAdapterConfig.getViewType], associate your View Types to different "views"
* [CustomViewAdapterConfig.viewHolderCreate], and final bind or set you data to the view [CustomViewAdapterConfig.bind] via callback/closures
*/
open class CustomRecyclerAdapter<T, VH : CustomViewHolder>(
val list: List<T>,
configurator: ()->CustomAdapterConfig<T, VH>
):RecyclerView.Adapter<VH>()
{
val config = configurator()
override fun getItemViewType(position: Int) =
config.getViewType?.invoke(position) ?: super.getItemViewType(position)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH {
return CustomViewHolder(
config.viewHolderCreate!!(parent, viewType)
) as VH
}
override fun onBindViewHolder(holder: VH, position: Int) {
config.bind(holder, position, list)
}
override fun getItemCount(): Int = list.size
}
open class CustomAdapterConfig<T, VH : CustomViewHolder>(
/** Callback to handle creating on views via ViewDataBinding*/
var viewHolderCreate: ((parent: ViewGroup, viewType: Int) -> View)? = null,
/** Do things like (holder.itemView as CustomView)tv.text = "Hello World" here*/
var bind: (holder: VH, position: Int, list: List<T>) -> Unit,
/** Set types for use in [viewHolderCreate]. return the viewType*/
var getViewType: ((position: Int)-> Int)? = null
)
open class CustomViewHolder(view: View): RecyclerView.ViewHolder(view)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment