How to migrate from Kotlin Synthetics to View Binding?

If you are keeping with android dev news you might know that starting Kotlin 1.4.20 android Kotlin extensions plugin has been deprecated along with kotlinx.synthetics.

What is Android-kotlin-extensions used for and why they are deprecated?

The android- kotlin- extensions are used for synthetics to replace findViewById and the parcelize annotation (@Parcelize) to remove the boilerplate code and easily create parcelables.

Now there are some major drawbacks when it comes to using kotlin synthetics.

  • They pollute the global namespace.
  • They don’t expose nullability information.
  • They only work in Kotlin code.

What is the alternative for Kotlin Synthetics?

Google recommends that you use View Binding.

View Binding is a feature that allows you to replace findViewById, once the view binding is enabled in the module, it generates a binding class for each XML layout file present in that module, In an instance of a binding class contains direct references to all the views that have an ID in the corresponding layout.

How to migrate from Kotlin Synthetics to View Binding?

To implement View Binding I have a created a project with single activity with a fragment that contains a textView in the layout.

1.PNG

2.PNG

Step 1: Open your app build.gradle file and add this build feature after that sync the project.

3.png

Step 2: After syncing, new classes will be generated for your layout now add this code in the fragment.

4.png

So what's happening in this code snippet:

  1. I have created a private variable with the name _binding with the type variable being FragmentBaseBinding this class was automatically generated by our View Binding then I created a read-only variable name binding without an underscore to get value from the binding.

  2. Inside the onCreateView method, I have used _binding variable to call FragmentBaseBinding with method name inflate and then pass the inflater after that I return the reference of the root view.

  3. Here I got the reference to the view using the binding variable tv_Title from the layout.

  4. Then I have call onDestroyView() inside this onDestroyView() I have set _binding variable to null so whenever we will destroy our fragments we set its value to null in order to avoid memory leaks.

So this is an example of how you can easily use view binding inside a fragment, note that as of me writing this post you can still use Kotlin-Android-Extensions in your project till September 2021.