在不同模块中使用的 Android 数据绑定(bind)

标签 android layout data-binding module include

现在我有三个模块,模块A,B,C。模块A编译模块B,模块B编译模块C。模块C中有一个布局(layout_c.xml)。然后我在模块A中使用layout_c.xml布局(layout_a.xml)。

  1. 有layout_c.xml `

    </variable>
    
    <variable
        name="handler"
        type="xxxxxx">
    
    </variable>
    

    <RelativeLayout
        ......
    </RelativeLayout>
    

    `

  2. 有layout_a.xml

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

  3. 问题: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
    }

}

应用解决方案的项目结构:

  1. 有一个库模块,和多个“应用程序模块” (也就是可以运行的手机或平板电脑的 Android Studio 模块) 在同一项目中使用该库中的 Activity/布局

  2. 库项目在/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/

相关文章:

Android 计时器滴答一次后停止

android - 更改android中alertdialog的标题大小?

c# - 使用绑定(bind)禁用特定的 DataGrid 单元格

angularjs - Angular 数据在 $http.post 成功方法中没有绑定(bind)

c# - 在 WPF 中填写所有字段之前,表单验证禁用提交按钮

java - Android 应用程序崩溃并出现错误 java.lang.RuntimeException : Unable to instantiate activity ComponentInfo

java - 来自 EdittextPreference 的文本

android - Canvas.drawText 无法从 R.string 获取值

android - 结合 Canvas 和布局 (Android)

html - 具有两个文本标签的框的 CSS 布局?