Created
December 23, 2014 05:11
-
-
Save rlac/c7656b8e73829fa28023 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 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