关于 android:DataBinding 库包含在没有变量的情况下不起作用

DataBinding library include don't work without variable

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

buttons.xml:

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

main.xml:

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

但我试了一下,报错:

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

我有附带的工具栏:

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

    <data>

        <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}"/>

怎么了?

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

相关讨论

  • 您是否使用最新版本的数据绑定库..?实施方式已更改。请同时发布相关的Java代码。 🙂
  • 嗨,我使用 2.0.0-beta4 插件,并使用 dataBinding { enabled = true } 打开绑定。所以我认为这是目前最新的。 @Amy,我认为这里不需要 java,因为您可以使用第一个布局中作为 ObservableField 传递的工具栏标题来重现它,并且您将看到相同的结果。
  • 对我也不起作用

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

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

查看他的博文了解更多信息。

相关讨论

  • 是的,我认为你是对的。这是误会。再次阅读他的答案,现在我看到他只是在谈论 ids,并且从 1.0-rc4 开始,不需要传递变量来通过 id 作为 binding.buttons.button1 来获取视图,就像在提到的版本之前一样。

以上是关于 android:DataBinding 库包含在没有变量的情况下不起作用的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>