Sometimes we can’t use kotlin synthetics library.

Maybe layout was changed during runtime, and int this case some new views can’t be accesseed with synthetics library, because view binding process starting on view creation stage.

Of course, we can use old findViewById way, but I try to use most powerful and elegant approach with kotlin extensions and lazy initializing:

fun <T : View> Activity.bindView(@IdRes idRes: Int): Lazy<T> = lazy(LazyThreadSafetyMode.NONE) { findViewById<T>(idRes) }

Now we can find view using this delegate:

val screenText: TextView by bindView(R.id.screenText)

or:

val screenText by bindView<TextView>(R.id.screenText)

That’s perfect!

Leave a Reply