双向DataBinding在viewholder中无法正常工作

Amg*_*rry 5 android android-databinding

所以我有一个带有复选框的viewHolder,这是我的viewModel

@Bindable
var itemIsSelected: Boolean = isSelected
    set(value) {
        if (field != value) {
            field = value
            notifyPropertyChanged(BR.itemIsSelected) // this doesn't work
            notifyChange() // this one works
        }
    }
Run Code Online (Sandbox Code Playgroud)

这是我的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
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

所以会发生这样的设置是正常工作,因为当我按下复选框时它将支持字段设置为相应的值,但是当我设置支持字段(绑定功能中的注意代码)时,它不会触发ui更改我知道调用binding.executePendingBindings()可以解决问题但我的理解是notifyPropertyChanged(BR.itemIsSelected)不应该需要executePendingBindings调用,实际上如果我调用notifyChange而不是一切正常(但我认为这里有性能问题,因为它通知更改对所有属性而言)

小智 0

您的 ViewModel 类必须扩展BaseObservable类,并且使用 kotlin 您必须使用@get:Bindable注释。如果您不想用作BaseObservable父类,则使用ObservableField<Boolean>(). 您可以在https://developer.android.com/topic/libraries/data-binding/observability#kotlin中找到更多信息