Last active
March 25, 2018 17:52
-
-
Save Lamartio/45813c186db77857f20f9e7e558313a3 to your computer and use it in GitHub Desktop.
Easy RecyclerView binding with Anko layout
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
fun <T> ViewGroup.toAnkoViewHolder(createView: AnkoContext<ViewGroup>.(((T) -> Unit) -> Unit) -> View): AnkoViewHolder = | |
AnkoViewHolder.create(this, createView) | |
class AnkoViewHolder(itemView: View, private val onBind: (Any) -> Unit) : RecyclerView.ViewHolder(itemView) { | |
fun bind(item: Any) = onBind(item) | |
companion object { | |
@Suppress("UNCHECKED_CAST") | |
fun <T> create(parent: ViewGroup, createView: AnkoContext<ViewGroup>.(((T) -> Unit) -> Unit) -> View): AnkoViewHolder { | |
val binder = ViewHolderBinder() | |
val context = AnkoContext.create(parent.context, parent) | |
val view = context.createView { it.let { it as (Any) -> Unit }.let(binder::add) } | |
val holder = AnkoViewHolder(view, binder) | |
return holder | |
} | |
} | |
} | |
private class ViewHolderBinder : (Any) -> Unit { | |
var onBind: (Any) -> Unit = {} | |
override fun invoke(item: Any) = onBind(item) | |
fun add(next: (Any) -> Unit) { | |
onBind = onBind.let { previous -> { previous(it); next(it) } } | |
} | |
} |
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
data class User(val name: String, val age: Int) | |
class ExampleAdapter : RecyclerView.Adapter<AnkoViewHolder>() { | |
private val data: List<User> = listOf( | |
User("Danny", 26), | |
User("Diede", 25) | |
) | |
override fun getItemCount(): Int = data.size | |
override fun onBindViewHolder(holder: AnkoViewHolder, position: Int) = | |
data[position].let(holder::bind) | |
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AnkoViewHolder = | |
parent.toAnkoViewHolder<User> { onBind -> | |
verticalLayout { | |
val title = textView() | |
val description = textView() | |
onBind { user -> | |
title.text = user.name | |
description.text = "The user's age is: ${user.age}" | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment