Android databinding - How to get dimensions from dimens.xml

The problem here is not with dimensions, but with android:layout_marginBottom. There is no built-in support for any LayoutParams attributes. This was done to remove the "foot gun" that many might use to bind variables to LayoutParams and maybe attempt to use data binding to animate their positions this way.

Data Binding is perfect to be used in your example and you can easily add your own. It would be something like this.

@BindingAdapter("android:layout_marginBottom")
public static void setBottomMargin(View view, float bottomMargin) {
    MarginLayoutParams layoutParams = (MarginLayoutParams) view.getLayoutParams();
    layoutParams.setMargins(layoutParams.leftMargin, layoutParams.topMargin,
        layoutParams.rightMargin, Math.round(bottomMargin));
    view.setLayoutParams(layoutParams);
}

You would, of course, also add the left, top, right, start, and end BindingAdapters as well.


Almost the same solution, but using Kotlin:

In file BindingAdapters.kt add:

@BindingAdapter("layoutMarginBottom")
fun setLayoutMarginBottom(view: View, dimen: Float) {
    view.updateLayoutParams<ViewGroup.MarginLayoutParams> {
        bottomMargin = dimen.toInt()
    }
}

Usage in layout:

<LinearLayout
    app:layoutMarginBottom="@{viewModel.type == Type.SMALL ? @dimen/margin_small : @dimen/margin_large}"

You can write similar method for top, start, end margins.