gpt4 book ai didi

android - RecyclerView 项目未使用 LiveData 更新

转载 作者:行者123 更新时间:2023-12-04 17:29:52 26 4
gpt4 key购买 nike

我有一个使用数据绑定(bind)、livedata、room、kotlin 协程、 View 模型、导航组件和 Dagger 的应用程序。我有一项 Activity 和两个 fragment 。

ListFragment:在回收 View 中显示项目列表。

DetalFragment:显示项目详细信息,并可以使用保存按钮更新项目的某些字段。

问题是当我从 detailfragment 更新一些字段时,更改在 listfragment 中不可见,但是当我向下和向上滚动时,更改变得可见。

列表 fragment :

 @Inject
lateinit var viewModelFactory: ViewModelProvider.Factory
val viewModel: ListViewModel by viewModels {
viewModelFactory
}

override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val bindings = ListFragmentBinding.inflate(inflater, container, false).apply {
viewmodel = viewModel
}
bindings.lifecycleOwner = this
adapter = ItemsAdapter()
bindings.recyclerView.adapter = adapter
viewModel.items.observe(
viewLifecycleOwner,
Observer { adapter.submitList(it)})
return bindings.root
}

ListView 模型:

var items: LiveData<PagedList<Item>> = repository.items

存储库:

val items<PagedList<Item>>
get()=itemDao.getAllItemsPaged().toLiveData(pageSize=50)
fun getItemFlow(id: String): Flow<Item> = itemDao.getItemFlow(id)
suspend fun updateItem(item: Item) {
itemDao.updateItem(item)
}

ItemDao:

 @Query("SELECT * FROM item")
fun getAllItemsPaged(): DataSource.Factory<Int,Item>
@Query("SELECT * FROM itemWHERE id=:id")
fun getItemFlow(id:String):Flow<Item>
@Update
suspend fun updateItem(item:Item)

项目 fragment :

@Inject
lateinit var viewModelFactory: ViewModelProvider.Factory
val viewModel: ItemViewModel by viewModels {
viewModelFactory
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
viewModel.loadItem(args.itemId)
val bindings = ItemFragmentBinding.inflate(inflater, container, false).apply {
viewmodel = viewModel
buttonSave.setOnClickListener{viewModel. viewModelScope.launch {
viewModel.saveItem()
findNavController().navigateUp()
}}

}

bindings.lifecycleOwner = this
return bindings.root
}

项目 View 模型:

var item: LiveData<Item>? = null

fun loadItem(id: String) {
viewModelScope.launch {
item = repository.getItemFlow(id).asLiveData()
}
}

suspend fun saveItem() {
item!!.value!!.someField = "hi"
repository.updateItem(item!!.value!!)
}

最佳答案

问题出在项目适配器中。适配器需要正确实现 DiffUtil.ItemCallback

在这种情况下:

private val DIFF_CALLBACK = object : DiffUtil.ItemCallback<Contador>() {
// The ID property identifies when items are the same.
override fun areItemsTheSame(oldItem: Contador, newItem: Contador) =
oldItem.id == newItem.id

// Check the properties that can change, or implements the equals method in Item class
override fun areContentsTheSame(
oldItem: Item, newItem: Item) = oldItem.someField == newItem.someField
}

关于android - RecyclerView 项目未使用 LiveData 更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60726069/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com