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

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

问题描述:

我在我的项目中有多个模块,比如模块应用程序和模块A,它们充当模块应用程序的库。我使用数据绑定,并通过在各模块的build.gradle加入Android数据绑定包含来自不同模块的布局

dataBinding { enabled = true }

工作正常。

当我使用标签包含模块A的布局时发生问题。当我试图访问包含布局的数据绑定,它返回查看对象,而不是ViewDataBinding

Android studio autocomplete

然而,当我试图继续访问所包含的布局里面的ID,汇编工作正常即使IDE显示错误。我试过重建项目,无效缓存和其他一切。

Error on android studio

而且我敢肯定,已经遵循了如何实现数据绑定的规则。这是在模块应用的布局:

<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> 

而且对模块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> 
+0

IDE显示什么错误? –

+0

无法解析符号,基本上找不到它https://i.stack.imgur.com/afIQX.png – luthfihariz

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

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

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

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

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