Android 数据绑定:如何传递变量以包含布局

Android Data Binding: how to pass variable to include layout

Google 文档说变量可以从包含布局传递到包含布局的绑定中,但我无法使其工作但出现数据绑定错误 ****msg:Identifiers must have user defined 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>

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

documentation指定

Here, there must be a user variable in both the name.xml and contact.xml layout files

我假设您应该在包含的布局中包含这个:

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

Just create <variable for passing values to included layouts.

Like 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

包裹

对于硬编码字符串:

 android:label="@{`Test 123`}"