以下代码来自项目体系结构样本,您可以here看到它。
通常我会观察viewModel.items
并像代码A一样更新适配器。
在项目体系结构样本中,作者使用定制的@BindingAdapter app:items
,不确定(listView.adapter as TasksAdapter).submitList(items)
更改后是否会触发val items: LiveData<List<Task>>
,您能告诉我吗? / p>
val items: LiveData<List<Task>>
tasks_frag.xml
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/tasks_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
app:items="@{viewmodel.items}" />
TasksListBindings.kt
@BindingAdapter("app:items")
fun setItems(listView: RecyclerView, items: List<Task>?) {
items?.let {
(listView.adapter as TasksAdapter).submitList(items)
}
}
TasksFragment.kt
private fun setupListAdapter() {
val viewModel = viewDataBinding.viewmodel
if (viewModel != null) {
listAdapter = TasksAdapter(viewModel)
viewDataBinding.tasksList.adapter = listAdapter
} else {
Timber.w("ViewModel not initialized when attempting to set up adapter.")
}
}
代码A
viewModel.items.observe(this, Observer<List<Task>> {
adapter.submitList(it)
})