Skip to content

Instantly share code, notes, and snippets.

@vlastachu
Created September 8, 2017 18:36
Embed
What would you like to do?
class AnkoViewHolder<out V : AnkoComponent<ViewGroup>>(val parent: ViewGroup, val createUI: () -> V) {
class ViewHolder<out V : AnkoComponent<ViewGroup>>(val view: View, val ui: V) : RecyclerView.ViewHolder(view)
val ankoContext by lazy { AnkoContext.createReusable(parent.context, parent) }
val viewHolder by lazy {
val ui = createUI()
val view = ui.createView(ankoContext)
view.setupTapEffectForBG(true) // default for every item in application
// TODO some items may be disabled...
ViewHolder(view, ui)
}
}
abstract class AnkoAdapter<out V : AnkoComponent<ViewGroup>>(
val createUI: () -> V,
private val presentUI: (Int, V) -> Unit
) : RecyclerView.Adapter<AnkoViewHolder.ViewHolder<*>>() {
final override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = AnkoViewHolder(parent, createUI).viewHolder
override fun onBindViewHolder(holder: AnkoViewHolder.ViewHolder<*>, position: Int) = presentUI(position, holder.ui as V)
}
class AnkoListAdapter<out V : AnkoComponent<ViewGroup>, T>(
private var list: List<T>,
private val createUI: () -> V,
private val presentUI: (T, V) -> Unit
) : RecyclerView.Adapter<AnkoViewHolder.ViewHolder<*>>() {
var onClick: ((T) -> Unit)? = null
var onLongClick: ((T) -> Unit)? = null
override fun getItemCount() = list.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = AnkoViewHolder(parent, createUI).viewHolder
override fun onBindViewHolder(holder: AnkoViewHolder.ViewHolder<*>, position: Int) {
presentUI(list[position], holder.ui as V)
holder.view.onClick { onClick?.invoke(list[position]) }
holder.view.onLongClick {
onLongClick?.invoke(list[position])
onLongClick == null
}
}
fun resetList(newList: List<T>) {
list = newList
notifyDataSetChanged()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment