Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To display variables in the layout preview using data binding in Android, follow these steps:

  1. Add the data binding dependency to your project by adding the following code to your app-level build.gradle file:
android {
    ...
    dataBinding {
        enabled = true
    }
}
  1. Create a layout XML file and wrap its root view with the <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>
  1. Create a data binding class for the layout in step 2 by using the following code:
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!"
}
  1. Define the variables that you want to bind in your ViewModel class:
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.