Created
January 26, 2021 20:45
-
-
Save brh/a69f2ff9dbcb89a05da6c0ab2d7414fb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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