To display variables in the layout preview using data binding in Android, follow these steps:
android {
...
dataBinding {
enabled = true
}
}
<layout>
tag. Inside the <layout>
tag, define the views that you want to bind to the variables.<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/my_text_view"
android:text="@{viewModel.text}"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/my_button"
android:text="@string/my_button_text"
android:onClick="@{viewModel::onButtonClick}"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
</layout>
private lateinit var binding: MyLayoutBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = MyLayoutBinding.inflate(layoutInflater)
setContentView(binding.root)
val viewModel = ViewModelProviders.of(this).get(MyViewModel::class.java)
binding.viewModel = viewModel
// Now, you can use the views that you defined in the layout.
binding.myTextView.text = "Hello, World!"
}
class MyViewModel : ViewModel() {
var text = MutableLiveData<String>()
fun onButtonClick() {
text.value = "Hello, Data Binding!"
}
}
Now, you can see the preview of the layout with the value of viewModel.text
shown in the preview. When you run your app, the layout will be inflated with the actual value of viewModel.text
instead of the placeholder value shown in the preview.
Asked: 2023-07-07 19:38:16 +0000
Seen: 15 times
Last updated: Jul 07 '23