Junior — Middle
Explain the concept of DataBinding and its role in data binding in applications.
sobes.tech AI
Answer from AI
DataBinding is a mechanism that connects data from the model with user interface elements, allowing automatic UI updates when data changes and vice versa.
In Android, DataBinding allows declaring a connection between variables in the code and elements in XML layout. This reduces boilerplate code, such as findViewById calls and manual UI updates.
Example of using DataBinding in Android:
// layout/activity_main.xml
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="user"
type="com.example.User" />
</data>
<TextView
android:id="@+id/userName"
android:text="@{user.name}" />
</layout>
// In Activity
val binding: ActivityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)
binding.user = User("Ivan")
Thus, when the user.name property in the model changes, the text in the TextView updates automatically.