是的,Android Data Binding 可以跨模塊使用。要在跨模塊項(xiàng)目中使用 Android Data Binding,請(qǐng)按照以下步驟操作:
android {
...
dataBinding {
enabled = true
}
}
dependencies {
...
dataBinding {
implementation 'androidx.databinding:databinding:4.2.0'
}
}
apply plugin: 'kotlin-kapt'
android {
...
dataBinding {
enabled = true
}
}
dependencies {
...
kapt "androidx.databinding:compiler:4.2.0"
}
android.libraryVariants.each { variant ->
variant.outputs.all { output ->
def outputFile = output.outputFile
if (outputFile != null && outputFile.name.endsWith('.aar')) {
def bindingOutputDir = file("$buildDir/generated/data_binding")
bindingOutputDir.mkdirs()
outputFileName = "${outputFile.nameWithoutExtension}_databinding.aar"
output.outputFile = new File(bindingOutputDir, outputFileName)
}
}
}
<layout>
標(biāo)簽包裹根視圖,并在需要數(shù)據(jù)綁定的視圖上添加 android:id="@+id/binding"
屬性。例如:<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<!-- 在這里定義綁定的變量 -->
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- 在這里使用數(shù)據(jù)綁定 -->
</LinearLayout>
</layout>
LayoutInflater
的 inflate
方法創(chuàng)建視圖,并將生成的綁定類與視圖關(guān)聯(lián):// Java
LayoutInflater inflater = LayoutInflater.from(context);
MyBinding binding = DataBindingUtil.inflate(inflater, R.layout.my_library_layout, parent, false);
// Kotlin
val inflater = LayoutInflater.from(context)
val binding: MyBinding = DataBindingUtil.inflate(inflater, R.layout.my_library_layout, parent, false)
完成以上步驟后,您就可以在跨模塊項(xiàng)目中使用 Android Data Binding 了。