DEV Community

Cover image for Android viewBinding (Jim Wilson Course)
Sibusiso Khumalo
Sibusiso Khumalo

Posted on • Updated on

Android viewBinding (Jim Wilson Course)

ViewBinding

Hi All this is my first blog post. I am going to cover viewbinding for beginner coder who is using Jim Wilson course on PluralSight.

The first time you build your project using the basic layout on Android Studio 3.6 and above you will find this layout of your project. Please delete the code lines and the files marked in red.
Alt Text

You need to delete this code also in your content_main.xml because you design view will not render your view because of the fragment xml code that it is referencing
Alt Text

Your start project should look like this without the fragments and the source code that controls the fragments in mainActivity.
Alt Text

You are now ready to implement Jim Wilson code the only difference is how you will reference your views in your layout. If you you look in your res.layout folder you will see two files activity_main.xml and content_main.xml. In your activity_main.xml you will see an include state for content_main.xml you need to give it an id (marked in red).
Alt Text

you need to give it an id, if you type id in the code block android studio will give you an autocomplete tab
Alt Text

Now we can talk about viewBinding

ViewBinding is Android Studio way of referencing your views in your layout without using findViewById. It has the following advantages over findViewById:

  1. Type safety
  2. Null safety
  3. Compile time error report this means that you will see your errors during compile time instead of runtime

ViewBing is implemented by the followig code in your MainActivity.kt file
Alt Text

You use the binding variable to reference your views in layout eg Jim Wilson implements his code using koltin default referencing system that you can use with an empty activity. The basic activity that implemnets viewBinging and seems to discard the default kotlin reference system. This just means that you will not be able to reference your views in you layout like Jim Wilson.

val originalValue = textDisplayValue.text.toSting().toInt()

val newValue = orginalValue * 2

textDisplayedValue.text = newValue.toString()
Enter fullscreen mode Exit fullscreen mode

You will need to implement the code above by using the viewBinding variable >binding

val originalValue = binding.layout_content_main.textDisplayValue.text.toString().toInt()

val newValue = orginalValue * 2

binding.layout_content_main.textDisplayValue.text = newValue.toString()
Enter fullscreen mode Exit fullscreen mode

And this is the basics of using viewBinding to reference you views.

Discussion (0)