Junior — Middle
Explain what View Binding is in Android and what it is used for.
sobes.tech AI
Answer from AI
View Binding in Android is a mechanism that allows you to work safely and conveniently with user interface elements without the need to use findViewById().
When View Binding is enabled, a class is automatically generated for each XML layout file, containing references to all Views in that file. This enhances type safety and reduces the likelihood of errors related to incorrect type casting or typos in identifiers.
Example of using View Binding:
// Enable View Binding in build.gradle
android {
viewBinding {
enabled = true
}
}
// In Activity
private ActivityMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
binding.myButton.setOnClickListener(v -> {
// Handle click
});
}
Thus, View Binding simplifies UI work, makes the code cleaner and safer.