[英]Why Isn't My Bound Data Showing Up in Android XML?
I have a custom layout that I want to reuse in several places, so I want to be able to pass a title to it, since that's the only value that will actually change. 我有一个自定义布局,我想在几个地方重用,所以我希望能够将标题传递给它,因为这是唯一实际会改变的值。 I know I can do that by binding data, but I can't get the data to render.
我知道我可以通过绑定数据来做到这一点,但我无法获取要呈现的数据。
In my activity.main
I have: 在我的
activity.main
我有:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.r.e.MainActivity">
<include
layout="@layout/switch_preference_custom_title"
app:passedTitle="@{@string/hello_world}" />
</RelativeLayout>
</layout>
I have defined my custom layout as follows: 我已经定义了我的自定义布局如下:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" >
<data>
<variable
name="passedTitle"
type="String"/>
</data>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{passedTitle}" />
</RelativeLayout>
</layout>
I also added 我还补充道
dataBinding {
enabled = true
}
in my build.gradle. 在我的build.gradle中。 My project compiles and runs fine, and the layout does render (I can tell by giving it a background), but the text is an empty string.
我的项目编译并运行正常,布局确实呈现(我可以通过给它一个背景告诉),但文本是一个空字符串。
It looks like one final linking piece was missing. 看起来最后一个链接片丢失了。 Instead of having
而不是拥有
setContentView(R.layout.activity_main);
in MainActivity, one needs to declare 在MainActivity中,需要声明
DataBindingUtil.setContentView(this, R.layout.activity_main);
This connects the Data Binding library with the root layout, without which none of your data bindings will actually render. 这将数据绑定库与根布局连接起来,没有这些布局,您的数据绑定都不会实际呈现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.