databinding设置View的layout_width和layout_height属性You must supply a layout_width attribute错误

来源:互联网 发布:怎么认证淘宝联盟权限 编辑:程序博客网 时间:2024/04/29 10:48
        <TextView            android:layout_width="@{@dimen/text_width}"            android:layout_height="@{@dimen/text_height}"            android:background="#e6e6e6"            android:gravity="center"            android:text="my girl!" />


dimens.xml文件的内容:

    <dimen name="text_width">200dp</dimen>    <dimen name="text_height">80dp</dimen>

运行之后,出现问题:


碰到这类错误,setter for attribute,基本就是属性没有对应的setter,需要我们使用@BindingAdapter等来弄一个方法,进行绑定。

或者方法的参数写错了。


这里由于View里面是不存在layout_widht和layout_height的属性的,我们知道这个只有其实是通过父控件的布局参数设置的。

所以需要设置@BindingAdapter。

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

运行发生Binary XML file line#49: You must supply a layout_width attribute的错误:


其实从图中可以看到在DataBindingUtil.setContentView(this, R.layout.activity_main);初始化执行的时候,需要给对应TextView的属性layout_width和layout_height设置值。

而这里的setLayoutWidth()和setLayoutHeight()方法在初始化的时候并没有执行,所以TextView的这两个属性是没有值的。故报了上述的错误,解决方法也很简单,

给一个默认值就可以了。

        <TextView            android:layout_width="@{@dimen/text_width, default=@dimen/text_width}"            android:layout_height="@{@dimen/text_height, default=@dimen/text_height}"            android:background="#e6e6e6"            android:gravity="center"            android:text="my girl!" />

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

这样子就可以了。



参考文章:

http://stackoverflow.com/questions/35295120/android-data-binding-layout-width-and-layout-height


http://stackoverflow.com/questions/34769981/android-databinding-layout-width-you-must-supply-a-layout-width-attribut

0 0