Updated 8 days ago | GitHub
On this page

Reducing View Boilerplate with ViewBinding

Overview

The View Binding library makes it easy to reduce the need to use findViewById() lookups. Once this option is enabled in your project, special binding classes will be generated from any of your layout XML files. If you have a layout called activity_simple.xml, for instance, a special class called ActivitySimpleBinding will be generated that will have references automatically created for you. The official View Binding guide lists these advantages over findViewById():

  • Null safety: the binding class holds direct references to views, so there’s no risk of a null pointer exception from an invalid view ID (views present only in some configurations of a layout are marked @Nullable)
  • Type safety: each field’s type matches the view it references in the XML file, so there’s no risk of a class cast exception

As a result, mismatches between your layout and your code fail the build at compile time rather than crashing at runtime.

NOTE: the View Binding library is separate from the Data Binding Library, which provides two-way and layout variables support.

Setup

View binding is enabled per module. Add the following to the module-level build file (app/build.gradle.kts, or app/build.gradle in Groovy projects). The snippet below is the Kotlin DSL form from the official guide; its Groovy tab writes the line as viewBinding true:

android {
    buildFeatures {
        viewBinding = true
    }
}

Once you have enabled this option, sync Gradle and rebuild the project (Build -> Clean and Assemble Project with Tests in Android Studio Meerkat (2024.3) and later; the action was named Rebuild Project in earlier versions). You will need to rebuild your entire project in order to make sure the view binding classes are created.

Activity View Lookups

Once you have enabled and recompiled your project, the binding classes should be available to you. In this example, an ActivitySimpleBinding class should have been generated for an activity_simple.xml file. Instead of using setContentView(R.layout.activity_simple), we replace that line with a call to ActivitySimpleBinding.inflate():

class ExampleActivity extends AppCompatActivity {
  private TextView title;
  private ActivitySimpleBinding binding;

  @Override 
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // activity_simple.xml -> ActivitySimpleBinding
    binding = ActivitySimpleBinding.inflate(getLayoutInflater());

    // layout of activity is stored in a special property called root
    View view = binding.getRoot();
    setContentView(view);

    // set bindings more efficiently through bindings
    title = binding.title;       // was title = findViewById(R.id.title);
    title.setText("My title");

    // alternately, access views through binding when needed, instead of variables
    binding.title.setText("My title");

  }
}
class ExampleActivity : AppCompatActivity() {
  private lateinit var title: TextView
  private lateinit var binding: ActivitySimpleBinding  

  override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      
      // activity_simple.xml -> ActivitySimpleBinding
      binding = ActivitySimpleBinding.inflate(layoutInflater)
  
      // layout of activity is stored in a special property called root
      val view = binding.root
      setContentView(view)

      // set bindings more efficiently through bindings
      title = binding.title       // was title = findViewById(R.id.title)
      title.text = "My title"

      // alternately, access views through binding when needed, instead of variables
      binding.title.text = "My title"
  }
}

Fragment View Lookups

This can be done within Activity, Fragment, or Adapter classes. For example, fragment usage would look like:

public class FancyFragment extends Fragment {
  Button button1;
  Button button2;

  FancyFragmentBinding binding;

  @Override 
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    
    // fancy_fragment.xml -> FancyFragmentBinding
    binding = FancyFragmentBinding.inflate(inflater, container, false);

    // layout of fragment is stored in a special property called root
    View view = binding.getRoot();
    			 
    // TODO Use fields...
    // binding.
    return view;
  }

  @Override 
  public void onDestroyView() {
    super.onDestroyView();
    binding = null;
  }
}
class FancyFragment : Fragment() {
  private lateinit var button1: Button
  private lateinit var button2: Button

  // Used to inflate and destroy the view
  private var _binding: FancyFragmentBinding? = null

  // Used throughout the class
  private val binding get() = _binding!!

  override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
    
    // fancy_fragment.xml -> FancyFragmentBinding
    _binding = FancyFragmentBinding.inflate(inflater, container, false)

    // layout of fragment is stored in a special property called root
    val view = binding.root
    			 
    // TODO Use fields...
    // binding.
    return view
  }

  override fun onDestroyView() {
    super.onDestroyView()
    _binding = null
  }
}

Troubleshooting

  • If you are missing a view binding class even though it is imported, try Build -> Clean and Assemble Project with Tests (named Rebuild Project before Android Studio Meerkat).

References