The following is an example code demonstrating how data binding can be implemented in Android programming.
The XML layout file, activity_main.xml, can contain the following code using ConstraintLayout:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="<http://schemas.android.com/apk/res/android>">
<data>
<variable
name="user"
type="com.example.User" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tv_first_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{user.firstName}"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<TextView
android:id="@+id/tv_last_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{user.lastName}"
app:layout_constraintTop_toBottomOf="@id/tv_first_name"
app:layout_constraintStart_toStartOf="@id/tv_first_name"
app:layout_constraintEnd_toEndOf="@id/tv_first_name" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
The Kotlin code can contain the following code:
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
val user = User("John", "Doe")
binding.user = user
}
}
That's it! This simple code demonstrates how to use data binding with ConstraintLayout in Android programming.