Android Data Binding layout_width and layout_height

I solved it like this in Kotlin instead of Java.

Make a file called

MyBindings.kt

And put in:

@BindingAdapter("bind:customHeight")
fun setLayoutHeight(view: View, height: Float) {
    view.layoutParams = view.layoutParams.apply { this.height = height.toInt() }
}

And then you can use this in your layouts:

<EditText 
android:id="@+id/internalTopDisplay"
android:layout_width="match_parent"
bind:customHeight="@{loginVM.compact ? @dimen/verificationHeightCompact : @dimen/verificationHeightFull}"
android:layout_height="wrap_content"/>

According to the discussion on Android issue tracker, it is impossible to set layout height or width with data binding without creating custom binding adapters:

https://code.google.com/p/android/issues/detail?id=180666

The binding adapter needed for setting view height would look like that:

@BindingAdapter("android:layout_height")
public static void setLayoutHeight(View view, int height) {
    LayoutParams layoutParams = view.getLayoutParams();
    layoutParams.height = height;
    view.setLayoutParams(layoutParams);
}

When data binding is used, we strip values from the XML. You can add a default value to be used when it is stripped to avoid the issue.

see: http://developer.android.com/tools/data-binding/guide.html (bottom of the page).

android:layout_height="@{loginVM.compact ? @dimen/verificationHeightCompact : @dimen/verificationHeightFull, default=wrap_content}"

In Java

@BindingAdapter("layout_height")
public static void setLayoutHeight(View view, float height) {
    LayoutParams layoutParams = view.getLayoutParams();
    layoutParams.height = height;
    view.setLayoutParams(layoutParams);
}

And in your XML

app:layout_height="@{ viewModel.isBig ? @dimen/dp_20 : @dimen/dp_5 }"

import the app like this

xmlns:app="http://schemas.android.com/apk/res-auto"