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.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-07-07 19:38:16 +0000
Seen: 15 times
Last updated: Jul 07 '23
What is the method to show the dependencies in Java?
What does the "Invalid source release 1.7" error mean when using gradle for compilation?
What is the reason for the failure of Task :app:signReleaseBundle in React Native Android?
How do compileSdkVersion and targetSdkVersion differ from each other?
How can we add animation to the user interface using jetpack compose?