android - 如何使用数据绑定在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>
解决方案
你必须调用方法。不要在数据绑定中使用直接变量。所以你必须用下面的行替换你的代码。
android:layout_centerVertical="@{data.shouldCenter() ? true : false}"
你必须在你的模型上创建 getter 方法,如下所示:
boolean shouldCenter;
public boolean shouldCenter() {
return shouldCenter;
}
它对我有用。检查它并告诉它是否不起作用!
推荐阅读
- python-3.x - Visual Studio Code Python linting 不适用于 venv 和 wsl
- c# - 通过数组循环项目的最佳实践
- ruby-on-rails - 如何在控制器中使用“.where”和“.where.not”方法测试实例变量
- sql - SQL Server - 从一行获取结果到另一行
- google-chrome - 未选中 runtime.lastError: 无法建立连接。接收端不存在
- android - 防止通知响起或振动
- web - NGINX htpasswd 404 未找到
- c# - 当对象被禁用 Unity 时,.activeInHierarchy 的输出仍然为真
- python - django_saml2_auth 无法配置 /saml2_auth/acs/
- php - Laravel 5.7:为什么我的模型 create() 和 save() 方法在调用时会创建 2 条记录?