现在我有三个模块,模块A,B,C。模块A编译模块B,模块B编译模块C。模块C中有一个布局(layout_c.xml)。然后我在模块A中使用layout_c.xml布局(layout_a.xml)。
有layout_c.xml `
</variable> <variable name="handler" type="xxxxxx"> </variable>
<RelativeLayout ...... </RelativeLayout>
`
有layout_a.xml
<include android:id="@+id/layout_c" layout="@layout/layout_c"/>
问题:IDE 认为 bindingA.layoutC 返回一个 View 而不是数据绑定(bind)。模块 C 有 BR 类和所有数据绑定(bind)类。但是模块 A 没有。那么,我该怎么办?
LayoutABinding bindingA = DataBindingUtil.setContentView(this,R.layout.layout_a); newTitleBarViewModel.setDataBinding(bindingA.layoutC);
最佳答案
为了让数据绑定(bind)跨多个模块工作——在我的例子中——我必须确保每个 Android Studio 模块(库、手机/平板电脑等)在其相应的 build 中启用了数据绑定(bind)。 gradle
(不仅仅是库 .gradle 文件,因为这还不够),
像这样:
android {
...
defaultConfig {
...
}
buildTypes {
...
}
// Looks like this needs to be set in the app module that uses the lib
// The lib needs it for the layout binding code there
dataBinding {
enabled = true
}
}
应用解决方案的项目结构:
有一个库模块,和多个“应用程序模块” (也就是可以运行的手机或平板电脑的 Android Studio 模块) 在同一项目中使用该库中的 Activity/布局
库项目在/res/layout 下有依赖于数据绑定(bind)的 .xml,如下所示:
<TextView android:id="@+id/display_name_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="10dp" android:text="@={user.displayName}" android:textSize="20sp"/>
This one was a bit tricky to resolve. Especially in my case where I have multiple modules. After I applied this solution for the main module I was working with, I still continued getting build errors. Finally I noticed in all the error output that there was 1 other module - which I hadn't been working with - that also had the library as dependency , but was missing the data binding enable in
build.gradle
. When finally that was identified and addressed, the builds are working fine. I'm glad to have found this as it makes things a lot nicer when you can reuse layouts with data binding across multiple modules
关于在不同模块中使用的 Android 数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39760087/