View Binding

Why use View Binding?

In this article we look how to use View Binding to find and configure your views.

Since the beginning the findViewById(id: Int) have been used for finding the View object in Activities, Fragments and Views.

There is nothing wrong with this method. But View Binding has important advantages.

  • Null Safty: View Binding creates direct references to views, so there is no risk of a null pointer exception due to an invalid view ID.

  • Type Safty: Each binding class have types matching the views they reference in the XML file. So there is no risk of a class cast exception.

Missmatch between your layout and your code will result in compiler error, instead of error during runtime.

Enable View Binding

To add view binding to the project add this to the application Gradle build file.

android {
    ...
    viewBinding {
        enabled = true
    }
    ...
}

If you do not want a layout file to generate the view binding add this to the root layout.

<FrameLayout ... tools:viewBindingIgnore="true">
    ...
</FrameLayout>

Usage

If you add an id to you layout file, in this example activity_main.xml. The View Binding feature generate ActivityMainBinding.kt with a Button object call button.

<FrameLayout ... >
    <Button android:id="@+id/button"  />
</FrameLayout>

The generate file can than be used directly in the MainActivity as shown below.

fun View.bindOnClick(callback: () -> Unit) = this.setOnClickListener { callback() }

fun TextView.bindText(owner: LifecycleOwner, text: LiveData<String>) {
    text.observe(owner, Observer { this.text = it })
}

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // Get the view model
        val viewModel = ViewModelProvider(this).get(MainActivityModel::class.java)
        
        // Bind the on click and text to the view-model.
        ActivityMainBinding.inflate(layoutInflater).let {
            it.button.bindText(this, viewModel.numberOfClickText)
            it.button.bindOnClick(viewModel::onIncreaseCounter)
            setContentView(it.root)
        }
    }
}

You can find the source code to this example on GitHub