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

Sentry mobile image

App store rankings love fast apps - mobile vitals can help you get there

Slow startup times, UI hangs, and frozen frames frustrate users—but they’re also fixable. Mobile Vitals help you measure and understand these performance issues so you can optimize your app’s speed and responsiveness. Learn how to use them to reduce friction and improve user experience.

Read full post →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay