📝 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