31

谷歌文档说变量可能会从包含布局传递到包含布局的绑定中,但我无法使其工作,但得到数据绑定错误****msg:标识符必须具有来自 XML 文件的用户定义类型。处理程序缺少它。包含的 XML 如下所示:

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:bind="http://schemas.android.com/apk/res-auto">

<data>
    <import type="com.example.FocusChangeHandler"/>

    <variable
        name="handler"
        type="FocusChangeHandler"/>
</data>

<!-- Some other views  --->

   <include
            android:id="@+id/inputs"
            layout="@layout/input_fields"
            bind:handler="@{handler}"/>        
</layout>

并且包含的​​ XML 是这样的:

<layout xmlns:android="http://schemas.android.com/apk/res/android">
<EditText
   android:id="@+id/nameEdit"       
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"       
   android:onFocusChange="@{handler.onFocusChange}"/>
</layout>

我可以通过生成的绑定类从包含的布局中引用视图,但传递变量不起作用。

4

3 回答 3

22

只需创建<variable将值传递给包含的布局。

app:passedText="@{@string/app_name}"

例子

就像我想传递String给包含的布局一样。我将创建一个类型的变量String。请参阅String您的TextView. 例如,我创建passedText了。

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

    <data>
        // declare fields
        <variable
            name="passedText"
            type="String"/>
    </data>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@{passedText}"/> //set field to your view.

</layout>

现在将passedText字段添加到您的<include标签。

<?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">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >

        <include
            layout="@layout/layout_common"
            app:passedText="@{@string/app_name}" // here we pass any String 
            />

    </LinearLayout>
</layout>

请注意,两个布局(父级和包含)都应该用binding layout, 包裹<layout

于 2018-08-01T12:32:04.757 回答
14

文档指定

这里,name.xml 和contact.xml 布局文件中都必须有一个用户变量

我假设您应该在包含的布局中包含此内容:

    <data>
           <variable name="handler"
                     type="FocusChangeHandler"/>
    </data>
于 2016-02-18T21:38:13.303 回答
8

对于硬编码字符串:

 android:label="@{`Test 123`}"
于 2019-01-30T21:49:03.663 回答