Android 数据绑定包括来自不同模块的布局

lut*_*riz 6 data-binding android android-studio

我的项目中有多个模块,假设模块 app 和模块 A 充当模块 app 的库。我使用数据绑定并通过添加正常工作

dataBinding { enabled = true }

在每个模块 build.gradle 中。

当我使用标签从模块 A 包含布局时出现问题。当我尝试访问包含布局的数据绑定时,它返回 View 对象而不是 ViewDataBinding

Android Studio 自动完成

但是,当我尝试继续访问包含布局中的 id 时,即使 IDE 显示错误,编译也能正常工作。我试过重建项目,使缓存和其他一切无效。

android studio 上的错误

而且我确信已经遵循了如何实现 DataBinding 的规则。这是模块应用程序的布局:

<layout xmlns:android="http://schemas.android.com/apk/res/android>
    <LinearLayout
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:background="@color/light_gray"
       android:orientation="vertical">

        <include layout="@layout/included_layout" id="@+id/contact"/>
    </LinearLayout>
</layout>
Run Code Online (Sandbox Code Playgroud)

以及模块 A 上的布局:

<layout xmlns:android="http://schemas.android.com/apk/res/android>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:id="@+id/tv_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </LinearLayout>
</layout>
Run Code Online (Sandbox Code Playgroud)

Sam*_*Sam 0

很可能是构建顺序问题。您可能需要确保在父模块尝试访问其内容之前模块 A 已构建。

您在绑定中看到的是您分配给联系人的 ID。这很好,因为它找到了您尝试访问的布局。接下来它将查找联系人的绑定文件。根据您的命名约定,应该类似于 IncludedLayoutBinding。该文件内部将包含嵌套的 textView 作为 tv_text。

现在,如果您没有看到 tv_text,那是因为从未为子模块创建 IncludedLayoutBinding。

您确定您的子模块已正确启用数据绑定,并且您确定在尝试访问其值之前它已构建。

您可以检查 childModule/build/source/dataBinding 文件夹,以确保您看到已创建的 layoutBinding 类。我猜它目前不存在。