[英]notifyDataSetChanged not updating view
I am using viewModel in recycler view, but its not updating only if I enter and exist screen not in screen itself:我在回收站视图中使用 viewModel,但只有当我进入并存在屏幕而不是屏幕本身时,它才会更新:
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel = ViewModelProvider(requireActivity()).get(RideDataViewModel::class.java)
rideList.adapter = MyRideListItemRecyclerViewAdapter(viewModel.rides.value!!, object : OnItemClickListener {
override fun onItemClicked(ride: RideEntity) {
viewModel.setRide(ride)
findNavController().navigate(R.id.rideDataFragment)
}
})
viewModel.rides.observe(viewLifecycleOwner, {
if (it.isNotEmpty())
{
no_rides.visibility = View.GONE
rideList.adapter!!.notifyDataSetChanged() //Function called but no visible data
}
else
{
no_rides.visibility = View.VISIBLE
}
})
lifecycleScope.launch {
viewModel.setRides(DataBaseHelper.getAllRidesFromDB())
}
}
ViewModel:视图模型:
class RideDataViewModel : ViewModel() {
var rides= MutableLiveData<List<RideEntity>>(listOf())
fun setRides(item: List<RideEntity>) {
rides.postValue(item)
}
}
You don't show your adapters code, but you need to set the adapters underlying data/list using the it
reference before calling notifyDataSetChanged
您没有显示适配器代码,但您需要在调用notifyDataSetChanged
之前使用it
引用设置适配器底层数据/列表
if (it.isNotEmpty()) {
no_rides.visibility = View.GONE
rideList.adapter!!.data = it // something similar to set the list in your adapter to the new values
rideList.adapter!!.notifyDataSetChanged() //Function called but no visible data
}
Where are you setting the list on your adapter?你在哪里设置你的适配器上的列表? In your LiveData observer you're only calling notifyDataSetChanged()
, which will only make the RecyclerView redraw the items, but you don't set the items first so it has nothing to redraw.在您的 LiveData 观察者中,您只调用notifyDataSetChanged()
,这只会使 RecyclerView 重绘项目,但您没有先设置项目,因此它没有重绘。
I don't know how your adapter looks, but something along the lines of the code below should make it update我不知道您的适配器看起来如何,但是按照下面的代码行应该可以更新
if (it.isNotEmpty()) {
no_rides.visibility = View.GONE
rideList.adapter!!.list = it // Update the list in the adapter
rideList.adapter!!.notifyDataSetChanged() // Now this will have something to draw
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.