ButterKnife @BindString equivalent in Android data binding

179 Views Asked by At

In my source code I have the following ButterKnife annotation:

public class MyActivity extends AppCompatActivity {

    @BindString(R2.string.settings_progress)
    String progressText;
    .
    .
    .
}  

Now I've decided to switch to Android Data Binding.

What would the equivalent be if I use Android data binding?

Should I declare a variable inside <data></data> tags in the activities XML file?

1

There are 1 best solutions below

0
RestingRobot On

You need to use the Data Binding Library

The basic usage is like this:

findViewById<TextView>(R.id.sample_text).apply {
    text = viewModel.userName
}

Or in XML

<layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">
    <data>
        <variable
            name="viewmodel"
            type="com.myapp.data.ViewModel" />
    </data>
    <TextView
        android:text="@{viewmodel.userName}" />
</layout>

Both of these approaches require using a ViewModel to connect the binding. However, I believe with the first approach you can bind to any observable property, (not 100% sure about the details on that).