如何使用数据绑定在relativelayout中设置layout_centerVertical

How to use data binding to set layout_centerVertical in relativelayout

假设我的视图可能在 RelativeLayout 中垂直居中对齐。我想使用数据绑定来实现这一点。

android:layout_centerVertical="@{data.shouldCenter ? true : false}"

我正在使用上面的方法 data binding error ****msg:Identifiers must have user defined types from the XML file. center is missing it ****\ data binding error ****。我应该如何让它工作?

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

        <import type="android.view.View" />

        <variable
            name="data"
            type="com.test.MainViewModel" />
    </data>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{data.title}"
            android:layout_centerVertical="@{data.shouldCenter ? true : false}"
            android:textColor="@{data.titleTextColor}"
            android:visibility="@{data.title != null ? View.VISIBLE : View.GONE}" />

        <TextView
            android:id="@+id/msg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/title"
            android:layout_marginLeft="@dimen/marginLarge"
            android:layout_marginTop="@dimen/marginSmall"
            android:text="@{data.message}"
            android:visibility="@{data.message != null ? View.VISIBLE : View.GONE}" />

    </RelativeLayout>
</layout>

你必须调用方法。不要在数据绑定中使用直接变量。所以你必须用下面几行替换你的代码。

 android:layout_centerVertical="@{data.shouldCenter() ? true : false}"

并且您必须在您的模型上创建 getter 方法,如下所示:

boolean shouldCenter;

public boolean shouldCenter() {
    return shouldCenter;
}

它适合我。检查它并判断它是否不起作用!

我有另一个解决方案,那就是使用BindingAdapter

@BindingAdapter(" android:layout_centerVertical")
public static void setCenterVertical(View view, boolean isCenterVertical) {
    RelativeLayout.LayoutParams layoutParams =
            (RelativeLayout.LayoutParams) view.getLayoutParams();
    layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT,
            isCenterVertical ? RelativeLayout.TRUE : 0);
    view.setLayoutParams(layoutParams);
}

并将其用作:

<TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{data.title}"
            android:layout_centerVertical="@{data.shouldCenter}"
            android:textColor="@{data.titleTextColor}"
            android:visibility="@{data.title != null ? View.VISIBLE : View.GONE}" />

希望这对您有所帮助