Sometimes, on some reasons, we can’t use kotlin synthetics library to find views in layout. For example, layout can be programmatically changed on runtime, and some views cannot be binded with synthetics, because view binding works on view created. So, we can simply use old good findViewById()  method, but better approach is using simple extension with lazy initialization:

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

Now we can simply find views using this delegate:

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

or

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

That is more useful and pretty fine 🙂

Leave a Reply

Close Menu