liangfeidotme / MasteringAndroidDataBinding

A comprehensive tutorial for Android Data Binding
http://liangfei.me
MIT License
2.59k stars 497 forks source link

如何绑定dimension数据? #5

Closed ydcool closed 8 years ago

ydcool commented 8 years ago

例如 android:layout_height="@{myView.height}"

这样直接写时编译报错:

Error:Execution failed for task ':app:compileDebugJavaWithJavac'. java.lang.RuntimeException: Found data binding errors. _/ data binding error _msg:Cannot find the setter for attribute 'android:layoutheight' with parameter type float. file:../example.xml loc:29:45 - 29:63 ***\ data binding error ***_

求指点

liangfeidotme commented 8 years ago

谢谢你提出这个问题 @Ydcool

我想到了一个利用 BindingAdapter 的解决方案,不知道是否符合你的要求。

原因

因为 android:layout_width 是由 parent view 设置,而 Data Binding 只会设置当前 View 的属性,所有会报错并提示找不到 setter

解决方案

首先想到是利用 @BindingAdapter 注解对 android:layout_width 进行适配,结果报了运行时错误,因为每个 View 必须提供系统的 android:layout_width 属性,所以不能进行适配。

java.lang.UnsupportedOperationException: Binary XML file line #18: You must supply a layout_height attribute.

改成自定义属性 - bind:layout_height 就可以了。

java

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

xml

<View
    android:background="@{isError.get() ? @color/red : @color/white}"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layout_height="@{height}" />

参考

ConversionsActivity.java

其实这个问题已经有人 issue 给 Android 团队了 - Android Databinding cannot set the layout_width (layout_height) property and ImageView src property

ydcool commented 8 years ago

Bravo ! 这个方法真不错👍 非常感谢