In Android projects written with Kotlin, you can replace findViewById<ViewType>(R.id.view_id)
calls by simply writing view_id
. The Kotlin Android Extensions plugin adds this synthetic extension property automatically to Activities, Fragments, Views, and classes with the LayoutContainer
interface.
The performance issue
Views don’t cache the extension property. Using view.view_id
is equivalent to calling findViewById
every time and looking up the view over and over again. This is an easy mistake to make in fragments, where you can get the root view.
The solution
Prefer the extension property on Activities and Fragments as those are cached. You can identify which version you use based on the import statement.
Using LayoutContainer
with any class
Classes with the LayoutContainer
interface can also cache synthetic extension properties. Just provide a getter for the root view object in containerView
, and everything else will work just like Activities and Fragments.