RecyclerView 适配器不使用数据绑定更新数据
RecyclerView adapter doesn't update data with databinding
请帮我解决一个问题。
我有 activity.xml 文件和 recyclerView,我设置了一个适配器,如:
<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 上看到空的适配器,所以我猜绑定不能正常工作..
这是一个愚蠢但不明显的错误,但问题已解决:)
我忘了为我的 recyclerView 添加布局管理器,例如:
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
在 xml 中,或者您可以通过编程方式进行。
**它发生了:)
请帮我解决一个问题。 我有 activity.xml 文件和 recyclerView,我设置了一个适配器,如:
<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 上看到空的适配器,所以我猜绑定不能正常工作..
这是一个愚蠢但不明显的错误,但问题已解决:) 我忘了为我的 recyclerView 添加布局管理器,例如:
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
在 xml 中,或者您可以通过编程方式进行。 **它发生了:)