本文介绍了为什么在Android中应用首先调用的ViewModel观察者?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
查看代码:
class ProductFragment : Fragment(R.layout.fragment_product) {
private val viewModel by viewModels<ProductViewModel>()
private lateinit var adapter: ProductAdapter
private var productList: List<Products> = ArrayList()
private var _binding: FragmentProductBinding? = null
private val binding get() = _binding!!
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
_binding = FragmentProductBinding.bind(view)
adapter = ProductAdapter(context, productList)
binding.apply {
recyclerView.setHasFixedSize(true)
recyclerView.adapter = adapter
showLog("LIST1: "+ productList.size)
}
viewModel.product().observe(viewLifecycleOwner) {
productList = it
adapter.notifyDataSetChanged()
}
}
在"it"内部我的尺寸正确,但问题是"recyclerView.adapter = adapter"首先调用而不是观察者,所以适配器中getItemCount的大小始终为0.
Inside "it" I'm getting correct size, but the thing is "recyclerView.adapter = adapter" is calling first instead of observer, so getItemCount size is always coming 0 inside adapter.
推荐答案
已解决:
@AndroidEntryPoint
class ProductFragment : Fragment(R.layout.fragment_product) {
private val viewModel by viewModels<ProductViewModel>()
private var _binding: FragmentProductBinding? = null
private val binding get() = _binding!!
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
_binding = FragmentProductBinding.bind(view)
viewModel.product().observe(viewLifecycleOwner, Observer { productList ->
binding.recyclerView.also {
it.setHasFixedSize(true)
it.adapter = ProductAdapter(context, productList)
}
})
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
这篇关于为什么在Android中应用首先调用的ViewModel观察者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!