布局中的算术运算 - Android 数据绑定

Arithmetic operations in layout - Android Data Binding

我正在尝试在数据绑定中使用算术运算:

<Space
    android:layout_width="match_parent"
    android:layout_height="@{2 * @dimen/button_min_height}" />

不幸的是我得到了:

Error:(47, 47) must be able to find a common parent for int and float 

有什么想法吗?

您应该以编程方式执行此操作。在您的 xml 文件中,将 android:id 属性添加到您的 Space 视图:

<Space
    android:id="@+id/space"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

在您的 Java class 中,您应该这样写:

Space space = findViewById(R.id.space);
space.getLayoutParams().height = 2 * getResources().getDimension(R.dimen.button_min_height);
space.requestLayout();

因为你正在执行int * float操作,所以2是int值,而@dimen/button_min_height会给你float值。但是 android:layout_height 将仅接受 float 值。

您可以像这样创建自定义绑定方法:

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

并在您的 xml 代码中

android:layout_height="@{(float)2 * @dimen/activity_vertical_margin}"

将 2 转换为 float 这样就不会出现任何转换错误。

从上面的代码中您将得到 RunTimeException : You must supply a layout_height attribute.,为了解决该错误,请将 default 值提供给 layout_height

android:layout_height="@{(float)2 * @dimen/activity_vertical_margin, default=wrap_content}"

也参考this official docs for default attribute concept, or you can refer