Step #7: Using View Binding in Our Activity

Next, modify onCreate() of MainActivity to look like this:

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    val binding = ActivityMainBinding.inflate(layoutInflater)

    setContentView(binding.root)
  }

The class code-generated by view binding is based off of the name of the layout resource. The lower_snake_case portion of the name is converted into UpperCamelCase, then gets Binding appended to it. So, activity_main becomes ActivityMainBinding.

Originally, onCreate() used setContentView(R.layout.activity_main). “Under the covers”, this would use a LayoutInflater to “inflate” activity_main, creating a tree of widgets and containers based on what is in the layout resource file. setContentView() would then take the root of that hierarchy and use it for rendering the UI.

Our two replacement lines do the same thing, in the end. The inflate() function on the ActivityMainBinding class inflates the activity_main layout using a LayoutInflater. It gets that LayoutInflater from us as a parameter to inflate(), and we get one via layoutInflater from the activity. The ActivityMainBinding object that we get back from inflate() has a root property, and we pass that to setContentView() to display our view hierarchy. The only effective difference between what we had and what we now have is that we have the binding object, and we can use that to reference the widgets inside of the layout, such as using binding.toolbar to get to our Toolbar.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.