Make Android View Binding great with Kotlin

Simplify usage of Android View Binding with Kotlin Property Delegates and solve behavior of Fragment’s ViewLifecycleOwner

Kirill Rozov
ProAndroidDev

--

View Binding is a new feature in Android Studio 3.6, but this isn’t true at all. View Binding is a lighter variant of Android Data Binding. Why do we need View Binding? The answer is performance. Many developers useAndroid Data Binding only to have reference to views from Layout XML and ignore other features of the library. Code generation in View Binding is faster. But the default way of its usage isn’t so good.

View Binding: default way

Let’s look at the usage of View Binding in Fragment. We have a layout resource profile.xml (content isn’t important). Generated View Binding for the layout has name ProfileBinding. The default use of the binding will be the next:

I disliked the next

  • Code with creating and destroying viewBinding
  • Copy-paste: every Fragment has the same code
  • viewBinding property is nullable and mutable. Isn’t good

Let’s use Kotlin Power and fix all of that

Kotlin Delegated Property

Using Kotlin Delegated Properties we can reuse part of code and simplify tasks. I used it to simplify the usage of ViewBinding. I have made a delegate that wraps the creation and destroying of aViewBinding :

Using the delegate I’ve refactored ProfileFragment :

The task has been solved. What could go wrong?

Something went wrong …

After the refactoring, I need to clean views inside viewBinding:

But as a result, I’ve gotten state that reference to ViewBinding inside the delegated property is null. The reason is how ViewLifecycleOwner of a Fragment notifies about ON_DESTROY lifecycle event. The event occurs before Fragment.onDestroyView(), that’s why I need to clear viewBinding only after all operations on the main thread will complete. It can be done using Handler.post. The fixed delegate is

Android View Binding is a very good solution to remove findViewById(). The library killed Butter Knife. A combination of it with the power of Kotlin Delegated Property will make your code cleaner and readable. All source code can be found here and you can use the solution in your project and adopt it.

You can find the soultion as library here:

Do you want to know more about Android development? Subscribe to Android Broadcast Telegram Channel (Russian) or English version.

--

--