Kotlin – How to Use ViewBinding in Android

πŸ“ Introduction

Tired of using findViewById() for every UI element? ViewBinding is here to help!
In this post, you’ll learn how to enable and use ViewBinding in your Android project with Kotlin. It’s faster, safer, and helps you write cleaner code.

βš™οΈ What is ViewBinding?

ViewBinding is a feature that generates a binding class for each XML layout file. This allows you to access views directly, without needing findViewById() or Kotlin synthetics.

βœ… Safe – No risk of NullPointerException
βœ… Fast – No runtime overhead
βœ… Easy – One line of code per layout

πŸ”§ Step 1: Enable ViewBinding in build.gradle

Open your app-level build.gradle and add the following inside android {}:

Then Sync your project.

πŸ–ΌοΈ Step 2: Create a Layout File

Example: activity_main.xml

πŸ‘¨β€πŸ’» Step 3: Use ViewBinding in MainActivity.kt

βœ… Benefits of ViewBinding

  • No more findViewById()
  • Safer null handling
  • Cleaner code with auto-generated classes
  • Supports fragments, recyclerviews, and custom views

πŸ” Use ViewBinding in a Fragment

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top