我是Kotlin的初学者,尝试在Android开发中实现MVVM设计模式。我必须在片段中实现Recyclerview。
由于API调用在ViewModel中进行观察,我们如何从ViewModel类设置适配器的值到RecyclerView呢?
我的片段类如下所示:
class NotesFragment : Fragment() {
lateinit var binding:FragmentNotesBinding
lateinit var viewModel:NoteListViewModel
companion object {
fun newInstance(param1: String): NotesFragment {
val fragment = NotesFragment()
val args = Bundle()
fragment.arguments = args
return fragment
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
binding = DataBindingUtil.inflate(inflater,R.layout.fragment_notes,container,false)
viewModel = NoteListViewModel(binding)
return binding.root
}
我们将绑定对象传递给ViewModel类并从ViewModel类中再次更新viewModel对象,这是一种好的实践吗?
private fun onSuccess(success: NoteResponse?) {
dataVisibility.value=View.VISIBLE
success.let {
noteAdapter= noteAdapter(documentResponse?.result,mContext)
binding.viewModel=this
}
}