Using view binding for type-safe UI access
View binding is Android’s built-in way to connect XML layouts to Kotlin or Java code. The build system generates a binding class for each layout, giving every view a declared type and a direct property. This removes fragile view lookups while keeping the UI definition in XML.
Instead of searching for a widget and casting it, an activity can access binding.lessonTitle as a TextView. If an identifier changes or a generated type differs from the expected type, the compiler exposes the problem before runtime. The result is clearer code with fewer opportunities for null, cast and misspelling errors.
Enabling view binding in an Android project
Enable the feature at the module level. In app/build.gradle.kts, add viewBinding under buildFeatures, then synchronise the project:
android {
buildFeatures {
viewBinding = true
}
}
After a rebuild, Android Studio generates classes such as ActivityMainBinding for activity_main.xml. Layout names become class names, while IDs become properties with camel-case names. Groovy build files use viewBinding true without the assignment operator.
View binding is not the same as data binding. It generates accessors, but it does not evaluate binding expressions, synchronise two-way state or automatically observe a LiveModel. That narrower purpose makes it a practical choice for conventional activities, adapters and dialogs.
Binding views in an activity
Give each widget used by code an ID in activity_main.xml. An activity should inflate the binding once, publish its root, and then work through the generated properties:
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.welcomeText.text = getString(R.string.welcome_message)
binding.continueButton.setOnClickListener {
binding.welcomeText.text = getString(R.string.lesson_started)
}
}
}
Here, welcomeText is statically known as a TextView, and continueButton as a Button. Calling setContentView(binding.root) preserves the normal XML layout hierarchy, including constraints and Material components. The inflated root is available before listeners are registered, so no extra findViewById call is required.
Keeping the binding as an activity property is safe because the activity and its view hierarchy are destroyed together. For code that outlives the activity, pass only the required data rather than retaining the binding or a view context. Java projects receive equivalent accessors such as getWelcomeText().
Working with dynamic lists safely
Lists need one binding class per row layout, not one class for the whole screen. A RecyclerView adapter can inflate ItemLessonBinding in onCreateViewHolder, then update the holder for each lesson:
data class Lesson(val title: String, val level: String)
class LessonAdapter(
private val lessons: List<Lesson>
) : RecyclerView.Adapter<LessonAdapter.LessonHolder>() {
class LessonHolder(
val binding: ItemLessonBinding
) : RecyclerView.ViewHolder(binding.root) {
fun bind(lesson: Lesson) {
binding.lessonTitle.text = lesson.title
binding.lessonLevel.text = lesson.level
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LessonHolder {
val binding = ItemLessonBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
return LessonHolder(binding)
}
override fun onBindViewHolder(holder: LessonHolder, position: Int) {
holder.bind(lessons[position])
}
override fun getItemCount(): Int = lessons.size
}
The holder owns its row binding, so lessonTitle and lessonLevel remain available in bind. A renamed row ID becomes a compiler error in the adapter rather than a runtime lookup failure. The adapter also receives a typed list of lesson models, keeping collection data separate from view references.
A custom ListView follows the same pattern: inflate the item binding in getView, assign the typed fields, and return binding.root. When using ListView or RecyclerView with large data sets, recycle or reuse rows rather than inflating an entire collection. View binding reduces casting errors; it does not replace correct adapter lifecycle and recycling practices.
Handling fragments and dialog interfaces
Fragments require extra care because their view can be destroyed while the fragment object remains. Hold the binding in a nullable property, create it in onCreateView, and clear it in onDestroyView:
private var _binding: FragmentLessonBinding? = null
private val binding get() = requireNotNull(_binding)
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val fragmentBinding = FragmentLessonBinding.inflate(inflater, container, false)
_binding = fragmentBinding
return fragmentBinding.root
}
override fun onDestroyView() {
_binding = null
super.onDestroyView()
}
A dialog can use a dedicated layout binding in the same way. Read the entered value only after the dialog is created, and keep the binding scoped to the dialog interaction rather than storing it on a long-lived fragment:
val dialogBinding = DialogFeedbackBinding.inflate(layoutInflater)
dialogBinding.feedbackEdit.setText("")
val dialog = MaterialAlertDialogBuilder(requireContext())
.setTitle(R.string.feedback_title)
.setView(dialogBinding.root)
.setPositiveButton(R.string.send) { _, _ ->
val feedback = dialogBinding.feedbackEdit.text.toString()
// Store the feedback.
}
.setNegativeButton(R.string.cancel, null)
.create()
dialog.show()
The generated properties apply equally to nested layouts, custom views and included layouts when those components have compatible IDs. This makes a form screen easier to audit: each reference shows its expected widget type, and the compiler verifies that the referenced view exists.
Avoiding nullability and lifecycle mistakes
The main compile-time benefit appears during refactoring. Renaming lessonTitle in XML immediately flags every old property access. Incorrect IDs and invalid property calls no longer survive silently until a user opens that screen.
Nullability still needs attention. When layout variants contain different views, a generated field may be nullable; a <merge> root also does not provide a normal root view. Check those conditions instead of forcing access with an unsafe cast.
View binding does not manage state, survive process death or observe data by itself. Combine it with ViewModel, SavedStateHandle and lifecycle-aware state when those concerns arise. The binding should remain a map to the current view hierarchy, not a store for all screen data.
Testing for Australian users and the local market
For teams serving Sydney, Melbourne and Brisbane, test on physical devices as well as emulators. A journey or delivery interface may need Australian distances in kilometres, kilometres per hour and map previews that reflect left-side traffic. Locale-aware number formatting avoids unexpected decimal separators or units.
Use Australian English and established date conventions such as dd/MM/yyyy. Time handling should use IANA zones including Australia/Sydney, Australia/Melbourne and Australia/Brisbane, because daylight-saving rules differ. Android’s locale-aware date and time formatters are safer than manually appending AEST.
The Australian Google Play market adds another release check. Digital purchase prices are presented in Australian dollars and generally include GST, while testing accounts and refund messages should use the same currency assumptions. Local content and shopping flows often resemble categories offered by Coles, Woolworths, ABC and SBS, but accessibility and empty states still need local testing.
A clean binding setup is therefore more than replacing method calls. It creates a stable contract between XML and code, helps automated builds catch mistakes, and makes adapters, fragments and dialogs easier to maintain. Run lint, unit tests and instrumented tests on the same binding classes used by the release build.