RecyclerView适配器不使用数据绑定更新数据

时间:2019-12-12 15:43:37

标签: android kotlin android-recyclerview recycler-adapter android-databinding

请帮助我解决问题。 我有带有recyclerView的activity.xml文件,我将其设置为:

<androidx.recyclerview.widget.RecyclerView
          android:id="@+id/recyclerView"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:background="@color/white"
          android:orientation="vertical"
          android:visibility="@{viewModel.recyclerVisibility}"
          app:adapter="@{viewModel.adapter}"
          app:layout_constraintTop_toBottomOf="@id/title" />

所以我在xml中设置了适配器,但是在我的viewModel中从服务器接收数据后,适配器没有更新:

someObservable.observeOn(AndroidSchedulers.mainThread()).subscribe {
     adapter.setItems(it)
     notifyPropertyChanged(BR.adapter)
})

要在xml中绑定适配器并对其进行访问,我的viewModel中有如下方法:

@Bindable
fun getAdapter(): SomeAdapter {
    if (adapter == null) {
        adapter = SomeAdapter(emptyList())
    }
    return adapter as SomeAdapter
}

在我的适配器中,我有方法来更新数据列表:

fun setItems(someData: List<SomeData>) {
    this.someData = someData
    notifyDataSetChanged()
}

那么这里出了什么问题?因为我在UI上看到空适配器,所以我猜绑定无法正常工作。

1 个答案:

答案 0 :(得分:0)

这是一个愚蠢但不明显的错误,但问题已解决:) 我忘了为recyclerView添加布局管理器,如:

app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
xml中的

或您可以通过编程方式进行。 **发生了:)