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

pme*_*aho 17 android-databinding

谷歌文档说,变量可以从包含布局传递到包含布局的绑定,但我无法使其工作,但是获取数据绑定错误****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>
Run Code Online (Sandbox Code Playgroud)

包含的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>
Run Code Online (Sandbox Code Playgroud)

我能够通过生成的绑定类引用包含布局的视图,但传递变量不起作用.

Khe*_*raj 8

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

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

就像我想传递String给包含的布局。我将创建一个type变量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>
Run Code Online (Sandbox Code Playgroud)

现在,将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>
Run Code Online (Sandbox Code Playgroud)

请注意,两个布局(父布局和包含布局)都应使用进行binding layout包装<layout

  • @DelacrixMorgan 请参阅 /sf/answers/3614354271/,请不要将 `DataBindingUtil` 用于片段和对话框。 (2认同)

Gen*_* Bo 8

对于硬编码字符串:

 android:label="@{`Test 123`}"
Run Code Online (Sandbox Code Playgroud)


小智 7

文件指定

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

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

    <data>
           <variable name="handler"
                     type="FocusChangeHandler"/>
    </data>
Run Code Online (Sandbox Code Playgroud)