Skip to content

Instantly share code, notes, and snippets.

@dnnyg33
Last active March 15, 2020 02:15
Show Gist options
  • Save dnnyg33/69a2faa1ab8a04faeba7a49967b90716 to your computer and use it in GitHub Desktop.
Save dnnyg33/69a2faa1ab8a04faeba7a49967b90716 to your computer and use it in GitHub Desktop.
EpoxyKotlinHolder with context
import android.content.Context
import android.view.View
import com.airbnb.epoxy.EpoxyHolder
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
/**
* A pattern for easier view binding with an [EpoxyHolder]
*
* See [com.airbnb.epoxy.kotlinsample.models.ItemEpoxyHolder] for a usage example.
*/
abstract class KotlinEpoxyHolder : EpoxyHolder() {
private lateinit var view: View
private lateinit var context: Context
override fun bindView(itemView: View) {
view = itemView
context = view.context
}
protected fun <V : View> bind(id: Int): ReadOnlyProperty<KotlinEpoxyHolder, V> =
Lazy { holder: KotlinEpoxyHolder, prop ->
holder.view.findViewById(id) as V?
?: throw IllegalStateException("View ID t for '${prop.name}' not found.")
}
/**
* Taken from Kotterknife.
* https://github.com/JakeWharton/kotterknife
*/
private class Lazy<V>(
private val initializer: (KotlinEpoxyHolder, KProperty<*>) -> V
) : ReadOnlyProperty<KotlinEpoxyHolder, V> {
private object EMPTY
private var value: Any? = EMPTY
override fun getValue(thisRef: KotlinEpoxyHolder, property: KProperty<*>): V {
if (value == EMPTY) {
value = initializer(thisRef, property)
}
@Suppress("UNCHECKED_CAST")
return value as V
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment