所以我有一个带复选框的 viewHolder 这是我的 View 模型
@Bindable
var itemIsSelected: Boolean = isSelected
set(value) {
if (field != value) {
field = value
notifyPropertyChanged(BR.itemIsSelected) // this doesn't work
notifyChange() // this one works
}
}
这是我的 viewHolder 类
inner class SpecialityItemViewHolder(val binding: ItemSpecialityFilterBinding): RecyclerView.ViewHolder(binding.root) {
fun bind(specialityItemViewModel: SpecialityItemViewModel) {
binding.viewModel = specialityItemViewModel
binding.executePendingBindings()
this.itemView.setOnClickListener {
binding.viewModel?.let {
it.itemIsSelected = !it.itemIsSelected // this doesn't trigger ui changes
}
}
}
}
xml
<?xml version="1.0" encoding="utf-8"?>
<layout>
<data>
<variable
name="viewModel"
type="packagename.ItemViewModel" />
</data>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="@dimen/vertical_margin_small"
android:paddingBottom="@dimen/vertical_margin_small"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<Checkbox
android:id="@+id/checkbox"
android:layout_width="25dp"
android:layout_height="25dp"
android:checked="@={viewModel.itemIsSelected}"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"/>
</android.support.constraint.ConstraintLayout>
</layout>
所以发生的是设置正常工作,因为当我按下复选框时,它将支持字段设置为相应的值 但是当我设置支持字段(绑定(bind)函数中的通知代码)时它不会触发 ui 更改我知道调用 binding.executePendingBindings() 会解决问题但我的理解是 notifyPropertyChanged(BR.itemIsSelected) 不需要调用 executePendingBindings ,实际上,如果我调用 notifyChange 而不是一切正常(但我认为这里存在性能问题,因为它通知所有属性的更改)
最佳答案
您的 ViewModel 类必须扩展 BaseObservable
类和使用 kotlin 你必须使用 @get:Bindable
注解。如果你不想使用 BaseObservable
作为父类然后使用 ObservableField<Boolean>()
.您可以在 https://developer.android.com/topic/libraries/data-binding/observability#kotlin 中找到更多信息
关于android - 两种方式 DataBinding 在 Viewholder 中无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53106201/