DEV Community

Cover image for TIL How to cache Kotlin Android view binding extensions
Tiger Oakes
Tiger Oakes

Posted on • Originally published at tigeroakes.com on

TIL How to cache Kotlin Android view binding extensions

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 extension property automatically to Activities, Fragments, Views, and classes with the LayoutContainer interface.

However, 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.

import kotlinx.android.synthetic.main.fragment_main.view.*

class MainFragment : Fragment(R.layout.fragment_main) {

  fun bindUi() {
    view.learn_button.setOnClickListener { ... }
    view.connect_button.setOnClickListener { ... }
  }
}
Enter fullscreen mode Exit fullscreen mode

Prefer the extension property on Activities, Fragments, and classes with the LayoutContainer interface as those are cached. You can identify which version you use based on the import statement.

import kotlinx.android.synthetic.main.fragment_main.*

class MainFragment : Fragment(R.layout.fragment_main) {

  fun bindUi() {
    learn_button.setOnClickListener { ... }
    connect_button.setOnClickListener { ... }
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)