MVVM Architecture

suggest change

Versions

This topic was documented against Android 2.1 through 7.1.

Remarks

Syntax quirks with DataBinding

When binding a viewModel function to a property in XML, certain function prefixes like get or is are dropped. For example, ViewModel::getFormattedText on the ViewModel becomes @{viewModel.formattedText} when bound to a property in XML. Likewise, ViewModel::isContentVisible becomes @{viewModel.contentVisible} (JavaBean notation).

The generated binding classes like ActivityMainBinding are named after the xml they're creating bindings for, not the java class.

Custom Bindings

In activity_main.xml the textColor attribute is set on the app namespace. A custom setter for textColor resolves a color resource id sent by the ViewModel to an actual color.

public class CustomBindings {

    @TargetApi(23)
    @BindingAdapter({"bind:textColor"})
    public static void setTextColor(TextView textView, int colorResId) {
        final Context context = textView.getContext();
        final Resources resources = context.getResources();
        final int apiVersion = Build.VERSION.SDK_INT;
        int color;

        if (apiVersion >= Build.VERSION_CODES.M) {
           color = resources.getColor(colorResId, context.getTheme());
        } else {
            color = resources.getColor(colorResId);
        }

        textView.setTextColor(color);
    }

}

For details on how this works check DataBinding Library: Custom Setters

Wait... there is logic in the XML

You could argue that the things I do in xml for android:visibility and app:textColor are wrong/anti-patterns in the MVVM context because there is view logic in my view. However I would argue it is more important for me to keep android dependencies out of my ViewModel for testing reasons.

Besides, what does app:textColor do? It only resolves a resource pointer to the actual color associated with it. The ViewModel still decides which color is shown based on some condition.

As for the android:visibility I feel because of how the method is named it is actually okay to use the ternary operator here. Because of the name isLoadingVisible and isContentVisible there is really no doubt about what each outcome should resolve to in the view. So I feel it is rather executing a command given by the ViewModel than really doing view logic.

On the other hand I would agree that using viewModel.isLoading ? View.VISIBLE : View.GONE would be a bad thing to do because you are making assumptions in the view what that state means for the view.

Useful Material

The following resources have helped me a lot in trying to understand this concept:

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents