如何使用ViewModel Android Kotlin将项目添加到RecyclerView



我有一个fragment,其中初始化了RecyclerView。在同一个fragment中,我将元素添加到该RecyclerView中。以下代码:

private lateinit var profileMenuList: MutableList<ProfileMenu>
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentProfileBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupRecyclerView()
}
private fun setupRecyclerView() {
profileMenuList = mutableListOf(
ProfileMenu(
title = "Favorite",
description = "What you liked",
icon = R.drawable.ic_outline_favorite_light
)
)

val adapter = ProfileAdapter(profileMenuList)
binding.rvProfileMenu.layoutManager = LinearLayoutManager(requireContext())
binding.rvProfileMenu.adapter = adapter
}

这也是Adapter:的代码

class ProfileAdapter(private val profileMenuList: List<ProfileMenu>): RecyclerView.Adapter<ProfileAdapter.ViewHolder>() {
class ViewHolder(private val binding: ItemProfileMenuBinding): RecyclerView.ViewHolder(binding.root) {
fun bind(menu: ProfileMenu) = with(binding) {
tvTitle.text = menu.title
tvDescription.text = menu.description
Glide.with(itemView.context).load(menu.icon).into(ivIcon)
}
companion object {
fun from(parent: ViewGroup): ViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val binding = ItemProfileMenuBinding.inflate(layoutInflater, parent, false)
return ViewHolder(binding)
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder.from(parent)
}
}

但是我想把fragment中的setupRecyclerView()函数的代码放入视图模型中。我该怎么做?

这不是一个好的实践。ViewModel不与UI元素交互。

正确使用;您可以在ViewModel中创建实时数据对象。然后从UI中观察对象。未将recylerview传递给ViewModel。

您不应该在视图模型中更新UI或使用任何上下文,您必须通过视图模型中的liveData对象传递列表,并在片段或活动中观察它,类似于以下内容:

class MyViewModel: ViewModel() {
val profileMenuList = MutableLiveData<List<ProfileMenu>>()
init {


profileMenuList .value = "YourDataRepository"
}
}

}

然后观察片段或活动中的liveData,阅读Android文档进行

最新更新