Skip to content

Instantly share code, notes, and snippets.

@rlac
Created December 23, 2014 05:11
Show Gist options
  • Save rlac/c7656b8e73829fa28023 to your computer and use it in GitHub Desktop.
Save rlac/c7656b8e73829fa28023 to your computer and use it in GitHub Desktop.
import android.view.View
import kotlin.properties.ReadOnlyProperty
import android.app.Activity
import kotlin.properties.Delegates
public fun Activity.bindView<T: View>(id: Int): ReadOnlyProperty<Any, T> = ViewVal(id)
public fun ViewHolder.bindView<T: View>(id: Int): ReadOnlyProperty<Any, T> = ViewVal(id)
public trait ViewHolder {
public val view: View;
}
public class ViewHolderImpl(v: View) : ViewHolder {
override val view: View = v
}
private class ViewVal<T: View>(val id: Int) : ReadOnlyProperty<Any, T> {
var value: T? = null
override fun get(thisRef: Any, desc: PropertyMetadata): T {
[suppress("UNCHECKED_CAST")]
if (value == null) {
value = when (thisRef) {
is Activity -> thisRef.findViewById(id)
is ViewHolder -> thisRef.view.findViewById(id)
else -> throw IllegalStateException("Unsupported type.")
} as T
}
return value!!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment