Android ViewBinding

ViewBinding is a resource that allows you to write better code that interacts with views. It generates a binding class for each XML layout file.

Usually you’ll use DataBinding. This replaces findViewById() and Butterknife.

ViewBinding Improvements

  • Null Safety since it creates direct reference to views
  • Type Safety the fields in each binding class have types matching the views they reference in the XML file.

Before all, let’s talk about ViewBinding vs DataBinding.

ViewBinding vs DataBinding

With DataBinding we bind data from the code to the views, as well as bind views to the code. If our requirement is just to bind views to the code, ViewBinding is faster and a lot easier to use.

That said, there’s nothing ViewBinding can do that DataBinding cannot do, but we cannot use ViewBinding to bind data from the code to the views and there will be no binding expressions, two way binding or binding adapters.

ViewBinding has two main advantages

  1. It’s easier to use.
  2. It’s faster at compile times.

Implementation

Activate it in the module-level gradle.plugin

android {
    buildFeatures {
        viewBinding = true
    }
}

If you want to ignore a layout file, just add this at root level

<LinearLayout
        tools:viewBindingIgnore="true" >
</LinearLayout>

Usage

The name of the binding follows this pattern result_profile.xml -> ResultProfileBinding.

It will create a field for each element that has an ID. It also includes a getRoot() providing a direct reference for the root view.

in activities

Perform this steps in the activity’s onCreate() method

  1. Call the static inflate() method for the generated binding class. This creates an instance of the binding class for the activity to use.
  2. Get a reference to the root view by calling the getRoot() method.
  3. Pass the root view to setContentView() to make it the active view on the screen.
public class MyActivityExample {

	private ResultProfileBinding binding;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// point 1
		binding = ResultProfileBinding.inflate(getLayoutInflater());
		// point 2
		View view = binding.getRoot();
		// point 3
		setContentView(view);
	}

}

in fragments

Perform the same steps in the fragment’s onCreateView() method.

public class MyFragmentExample {

	private ResultProfileBinding binding;
	
	@Override
	public View onCreateView(LayoutInflater inflater,
								ViewGroup container,
								Bundle savedInstanceState) {
		binding = ResultProfileBinding.inflate(inflater, container, false);
		return binding.getRoot();
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		binding = null;
	}

}

Resource(s)

https://developer.android.com/topic/libraries/view-binding