Older Android code accesses views with findViewById, which is verbose and not type-safe:
// Older approach — works, but easy to get wrong
val greetingText = findViewById<TextView>(R.id.greetingText)
Modern projects use ViewBinding instead, which generates a typed binding class for each layout automatically. Enable it in your module’s build.gradle.kts:
android {
buildFeatures {
viewBinding = true
}
}
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.greetingText.text = "Hello from ViewBinding!"
}
}
lateinit var tells the compiler “trust me, this will be assigned before it’s used” — appropriate here because binding genuinely can’t be created until onCreate runs, but must be accessible from other methods in the class afterward.
- Image
- SKU
- Rating
- Price
- Stock
- Availability
- Add to cart
- Description
- Content
- Weight
- Dimensions
- Additional information