Search code examples
androiddata-bindingandroid-databinding

Does data binding move UI logic out of the layouts?


I'm very new to data binding and am just beginning to have a look at the Android data binding library, and one thing in the documentation bugs me.

Using ViewModel components with the Data Binding Library allows you to move UI logic out of the layouts and into the components, which are easier to test.

Right after that, there's this - in the layout XML:

<CheckBox
    android:id="@+id/rememberMeCheckBox"
    android:checked="@{viewmodel.rememberMe}"
    android:onCheckedChanged="@{() -> viewmodel.rememberMeChanged()}" />

Maybe it's just me, but doesn't that onCheckedChanged property contain a lot more "logic" in the layout than the old fashioned way of calling setOnCheckedChangeListener() on a "dumb" layout from an activity or fragment? It all seems a bit contradictory. Can someone explain to me how data binding moves "UI logic out of the layouts" ?


Solution

  • Your ViewModel now holds the logic, which you can test independent of the UI and the UI can be tested with mocked ViewModels. Its not always less code, its more structured code following a pattern.