Android 数据绑定设置 alignParentTop

Android databinding set alignParentTop

我有以下布局(只剩下相关部分):

<RelativeLayout>
    <View android:layout_alignParentTop="true"/>
</RelativeLayout>

我尝试使用在 <data> 块中声明的变量设置 layout_alignParentTop 属性,如下所示:

<data>
    <variable
        name="condition"
        type="Boolean"/>
</data>

<RelativeLayout>
    <View android:layout_alignParentTop="@{condition}"/>
</RelativeLayout>

然而,在尝试编译时,android studio 表示如下:

Error: Cannot find the setter for attribute 'android:layout_alignParentTop' with parameter type java.lang.Boolean.

如何使用数据绑定变量设置 layout_alignParentTop 属性?

我不得不对此进行一些深入研究,我在 Google 代码中找到了一个 recent issue

引用一位项目成员的话:

We explicitly did not support data binding for layout properties, though you could technically add them yourself. The problem is that these can be easily abused with people trying to animate them.

To implement these for your application, create a binding adapter:

@BindingAdapter("android:layout_width")
public static void setLayoutWidth(View view, int width) {
  LayoutParams layoutParams = view.getLayoutParams();
  layoutParams.width = width;
  view.setLayoutParams(layoutParams);
}

在您的情况下,您只需要针对 alignParentTop 属性稍微调整一下:

@BindingAdapter("android:layout_alignParentTop")
public static void setAlignParentTop(View view, boolean alignParentTop) {
   RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
      RelativeLayout.LayoutParams.WRAP_CONTENT,
      RelativeLayout.LayoutParams.WRAP_CONTENT);

   if(alignParentTop) {
      layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
   }

   view.setLayoutParams(layoutParams);
}

这是未经测试的,但应该足以让您走上正轨。

@BindingAdapter("android:layout_alignParentLeft")
public static void setAlignParentLeft(View view, boolean alignParentLeft) {
    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
            view.getLayoutParams()
    );

    if (alignParentLeft) {
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
    }

    view.setLayoutParams(layoutParams);
}

此代码更通用,并不适用于每个视图wrap_content