Android View Binding — Complete Guide
In this tutorial, you'll learn about Android View Binding. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
The Problem
findViewById returns nullable views, leads to null checks everywhere, and doesn't catch type mismatches at compile time. You still write TextView name = findViewById(R.id.name) in every method.
Wrong Approach ❌
// findViewById mess
class MyActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val textView = findViewById<TextView>(R.id.text_view) // Nullable!
textView.text = "Hello" // Might crash if ID is wrong
}
// Duplicate findViewById in every method
fun updateTitle(title: String) {
val tv = findViewById<TextView>(R.id.text_view) as? TextView // Awful
tv?.text = title
}
}
Output: ClassCastException or NullPointerException from wrong IDs or types.
Right Approach ✅
// Enable in build.gradle: buildFeatures { viewBinding = true }
class MyActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.textView.text = "Hello" // Type-safe, non-null
}
fun updateTitle(title: String) {
binding.textView.text = title // Single binding reference
}
}
Output: Compile-time safe, no null checks needed, no findViewById calls.
Prevention
- Enable
viewBinding = truein your module'sbuild.gradle. - Use
Fragment'sonDestroyView()to null out the binding reference. - Use
_bindingbacking field pattern:private var _binding: FragmentBinding? = null. - Never mix
findViewByIdand View Binding in the same file.
Common Mistakes with view binding
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
These mistakes appear frequently in real-world Android code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro