0

正如 George Mount所说 ,从 1.0-rc4 开始,我们在使用数据绑定时不再需要 include 中的变量:

按钮.xml:

<layout xmlns:andr...>
   <Button
    android:id="@+id/button"
    ...." />

主.xml:

<layout xmlns:andr...
...
    <include layout="@layout/buttons"
            android:id="@+id/buttons"/>
....

但我试了一下,报错:

错误:(10, 31) 标识符必须具有来自 XML 文件的用户定义类型。工具栏视图模型缺少它

我有包含的工具栏:

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

    <data class="LoginPhoneFragmentBinding">

        <variable
            name="toolbarViewModel"
            type="ru.mobileup.myalarm2.binding.ToolbarViewModel"/>
    </data>

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

        <include
             layout="@layout/toolbar"
             android:id="@+id/toolbarBinding"/>

工具栏布局是:

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="@color/primary"
    android:theme="@style/ToolbarThemeOverlay"
    app:navigationIcon="@{toolbarViewModel.navigationIconResId}"
    app:navigationOnClickListener="@{toolbarViewModel.navigationOnClickListener}"
    app:title="@{toolbarViewModel.title}"
    app:menu="@{toolbarViewModel.menuResId}"
    app:menuListener="@{toolbarViewModel.onMenuItemClickListener}"/>

怎么了?

注意:我知道使用传递的变量一切正常。我试图弄清楚乔治提到的用途。

4

1 回答 1

0

我认为您误解了乔治在链接帖子上的回答;如果您想像@{toolbarViewModel.title}在包含的工具栏布局中那样引用它,您仍然需要该变量。

如果您在 build.gradle 中启用了 dataBinding 并将您的布局包装在一个额外的<layout>标签中,您将获得一个自动生成的ViewDataBinding类,其中包含对布局中具有 ID 的任何视图的解析引用(例如binding.toolbar,或类似的东西)。这不会自动为您绑定数据,但可以让您摆脱任何findViewById呼叫。

有关更多信息,请参阅他的博客文章

于 2016-07-13T14:54:46.767 回答