How does the new ViewBinding compare with the Kotlin Android Extensions with synthetic views bindings?
Apart from the NullSafety and TypeSafety provided by new ViewBindings, why should we consider ditching the Kotlin way of using synthetic bindings on Views?
Is the new ViewBinding more performant since it generates the Binding class beforehand?
Let's review the two.
import kotlinx.android.synthetic.main.<layout>.*
textView.text = "Hello, world!"
. These extensions work on: Activities
, Fragments
and Views
. private lateinit var binding
YourClassBinding
binding = YourClassBinding.inflate(layoutInflater)
inside Activity
's onCreate
and call setContentView(binding.root)
, or inflate it in Fragment
's onCreateView
then return it: return binding.root
binding.textView.text = "Hello, world!"
Kotlin Android Extensions and ViewBinding are type safe by definition, because referenced views are already casted to appropriate types.
Kotlin Android Extensions and ViewBinding are both null safe. ViewBinding doesn't have any advantage here. In case of KAE, if view is present only in some layout configurations, IDE will point that out for you:
So you just treat it as any other nullable type in Kotlin, and the error will disappear:
In case of Kotlin Android Extensions, layout changes instantly translate to generation of synthetic extensions, so you can use them right away. In case of ViewBinding, you have to build your project
In case of Kotlin Android Extensions, it is possible to import incorrect layout synthetic extensions, thus causing NullPointerException
. The same applies to ViewBinding, since we can import wrong Binding
class. Although, it is
more probable to overlook incorrect import than incorrect class name, especially if layout file is well named after Activity
/Fragment
/View
, so ViewBinding has upper hand here.
The Kotlin Android Extensions plugin allows us to obtain the same experience we have with some of these libraries, without having to add any extra code.
I think there is big misconception about ViewBinding being replacement for KAE. People hear big keywords and repeat them without verifying it beforehand. Sure, ViewBinding is best option for Java development right now (replacement for ButterKnife), but there is no or little advantage over KAE in Kotlin (see Incorrect layout usage section).
Side note: I'm sure DataBinding people will like ViewBinding :)