Android 如何使用MVVM体系结构,用房间中的数据填充微调器
我想知道用房间数据库中的数据填充任何微调器的最佳实践/方法 我还想使用ViewModel和LiveData(然后我将转到StateFlow!),但我对定义变量的正确顺序感到困惑 首先,我在视图模型中有以下内容:Android 如何使用MVVM体系结构,用房间中的数据填充微调器,android,kotlin,spinner,Android,Kotlin,Spinner,我想知道用房间数据库中的数据填充任何微调器的最佳实践/方法 我还想使用ViewModel和LiveData(然后我将转到StateFlow!),但我对定义变量的正确顺序感到困惑 首先,我在视图模型中有以下内容: val aniosLiveData = anioRepository.anios.asLiveData() // return LiveData<List<Anio>> 然后,在onViewCreated()中,我有一个包含绑定元素的块: binding.a
val aniosLiveData = anioRepository.anios.asLiveData() // return LiveData<List<Anio>>
然后,在onViewCreated()中,我有一个包含绑定元素的块:
binding.apply {
recyclerViewEnsayos.apply {
adapter = ensayosAdapter
layoutManager = LinearLayoutManager( requireContext())
setHasFixedSize(true)
}
spinnerAnio.apply {
adapter = aniosAdapter // <- Spinner adapter
}
}
binding.apply{
RecycleServiceWnsayos.apply{
适配器=ensayosAdapter
layoutManager=LinearLayoutManager(requireContext())
setHasFixedSize(真)
}
spinnerAnio.apply{
适配器=AnioAdapter//
AnioAdapter=ArrayAdapter(requireContext(),R.layout.spinner\u text\u项,spinnerData)
})
我需要在何处/何时声明“AnioAdapter”?例如:
//At class level
private lateinit var aniosAdapter : ArrayAdapter<Anio>
//在类级别
私有lateinit var aniosAdapter:ArrayAdapter
这是正确的方法吗?
还有一个更简单的
提前谢谢!
如果您需要在生命周期挂钩之外引用
AnioAdapter
,我建议您使用您提到的私有lateinit var
。当您首先正确初始化spinnerAnio
的适配器时,它不会追溯识别您对AnioAdapte所做的任何突变r
在执行lifecycle钩子之后。相反,您需要调整aniosLiveData
观察者,使其显示如下:
ensayosViewModel.aniosLiveData.observe(viewLifecycleOwner, {
binding.spinnerAnio.adapter = ArrayAdapter<Anio>(
requireContext(),
R.layout.spinner_text_item,
it
)
})
如果你可以保证你的观察者会被触发,private var aniosAdapter: ArrayAdapter<Anio>? = null
private var aniosAdapter:ArrayAdapter?=null
ensayosViewModel.aniosLiveData.observe(viewLifecycleOwner, {
binding.spinnerAnio.adapter = ArrayAdapter<Anio>(
requireContext(),
R.layout.spinner_text_item,
it
)
})
ensayosViewModel.aniosLiveData.observe(viewLifecycleOwner, {
aniosAdapter = ArrayAdapter(
requireContext(),
R.layout.spinner_text_item,
it
)
binding.spinnerAnio.adapter = aniosAdapter
})
private var aniosAdapter: ArrayAdapter<Anio>? = null