我在使用BindingAdapter在我的新应用程序中工作时遇到了一些问题。
我总是收到以下错误:
****/ data binding error ****msg:Cannot find the setter for attribute 'visible' with parameter type boolean
这是我的BindingAdapter:
object BindingAdapters {
@set:BindingAdapter("visible")
@JvmStatic
var View.visible
get() = visibility == View.VISIBLE
set(value) {
visibility = if (value) View.VISIBLE else View.GONE
}
}
这是XML中的视图生成问题的视图:
<TextView
android:id="@+id/tvDescription"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="@dimen/item_horizontal_margin_large"
android:text="@{viewModel.item.description}"
visible="@{viewModel.showGroup}"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toEndOf="@id/ctvDivision"
app:layout_constraintTop_toTopOf="parent" />
这是一个新项目,所以我从Android X开始,不需要进行迁移。
我在build.grade中有这一行:
annotationProcessor 'androidx.databinding:databinding-compiler:3.4.0-alpha09'
我正在使用gradle 3.2.11。
我不确定是否需要这个,但这是我正在膨胀我的绑定的代码:
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
setHasOptionsMenu(true)
binding = DataBindingUtil.inflate(
layoutInflater,
R.layout.fragment_good,
container,
false
)
val view = binding?.root
binding?.viewModel = viewModel
return view
}
所有其他标准数据绑定的东西都可以工作。一旦我尝试设置BindingAdapter它就会失败。
我读过SO,有些人声称数据绑定与X无法正常工作。但那些是10月份的帖子,有人声称它在同一篇文章中对他们有效。
我忘记了一些愚蠢的事情,还是真的还没有使用X?
我使用Kotlin(1.3.30),AndroidX,DataBinding和Gradle 3.4.0在小型新项目中重现问题
首先,Kotlin不能使用annotationProcessor
,必须用Kotlin Annotation Processing Tool替换:kapt
和kotlin-kapt
插件。
Kotlin documentation
然后在Gradle 3.1.0-alpha06中,Google自Gradle 3.2起默认包含了新版本的数据绑定编译器。
所以你不需要使用databinding-compiler
依赖(它是集成的)。
Android Developer documentation
但即使是整合,它总是需要kapt。
因此,在apply plugin: 'kotlin-kapt'
app文件的顶部添加build.gradle
并删除androidx.databinding:databinding-compiler
依赖项,应解决问题。 (它对我有用)
我遇到了同样的问题。如果您的绑定适配器是用Kotlin(而不是Java)编写的,那么您就不能再将Java原语布尔变量传递给它们(或任何原始Java类型)。将viewModel.showGroup更改为Java.lang.Boolean或最好是Kotlin布尔值。
我还注意到,如果你在数据绑定表达式中使用布尔表达式,例如visible="@{viewModel.showGroup && true}"
,那么它会输出一个Java原语布尔值,并且不再与Kotlin绑定适配器兼容。