Should we bind android views in Kotlin?

Viewed 222

Programming Java, we need to use findViewById function to access a view item, nowadays in Kotlin we simply use id for accessing view item, like if we have a textView with id "myTxt" we simply use myTxt.text = "Some Text"

In the other hand using findViewById function in Java would led to less efficient performance, so we're suggested to use binding view for performance improvements

now the question is:

Now that we do not use findViewById in kotlin, should we use binding, or this won't cause any efficiency in performance?

2 Answers

There are three common ways to get view references:

  • findViewById
  • synthetic view properties (Kotlin only)
  • view binding

I think you are mixing up view binding vs. synthetic view properties.

When you say in Kotlin we "simply use id", that is called synthetic view properties. That feature was created for convenience over findViewById, not for performance.

Google at some point removed references to synthetic view properties in their documentation, because it is Kotlin-only. It's also not great that they are not null-safe or type-safe. Null safety is usually expected in Kotlin code. And all the synthetic properties for all your views are available from anywhere, regardless of whether they are in the current layout.

Later, they added view binding as a Jetpack feature. This is also not added for performance, but convenience. It's preferable to findViewById because it's null-safe, type-safe, and gives you properties for the exact views that you have inflated, nothing more or less. View binding is not limited to Kotlin. You can use it in Java.

View binding in Kotlin is by default enabled in gradle module. To manually enable view binding in a module, set the viewBinding build option to true in the module-level build.gradle file, as shown in the following example:

android {

 buildFeatures {
     viewBinding true
  }
}

So if you are using Kotlin you should use the view binding instead of findViewById. It's lot easier and the number of code lines are reduced. Also it won't effect performance.

Related