首页 > 解决方案 > 如何使用数据绑定在relativelayout中设置layout_centerVertical

问题描述

假设我有可能是中心垂直对齐的视图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>

标签: androidandroid-databinding

解决方案


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

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

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

boolean shouldCenter;

public boolean shouldCenter() {
    return shouldCenter;
}

它对我有用。检查它并告诉它是否不起作用!


推荐阅读