[英]How to update a textView of recycler view with live data
I want to update a textview of the recycler view with a live data.我想用实时数据更新回收站视图的 textview。
how can I do this?我怎样才能做到这一点? I am a beginner please help我是初学者请帮忙
this is my viewModel class这是我的视图模型 class
class ViewModelClass : ViewModel() {
var rating = MutableLiveData<String>("NA")
}
I have a textView in a recycler view which I want to update after taking the text from the edit text but I could not do this because I can not get the reference of that textview in the MainActivity.我在回收站视图中有一个 textView,我想在从编辑文本中获取文本后对其进行更新,但我无法执行此操作,因为我无法在 MainActivity 中获取该 textview 的引用。
btnSave.setOnClickListener {
val rating : String = etRating.text.toString()
viewModel.rating.value = rating
}
Follow these steps:按着这些次序:
class MyAdapter: ListAdapter<String, MyAdapter.MyAdapterViewHolder>(DIFF_CALLBACK) {
class MyAdapterViewHolder(
private val binding: ItemSimplePosterBinding
): RecyclerView.ViewHolder(binding.root) {
// implementation here
}
companion object {
private val DIFF_CALLBACK = object : DiffUtil.ItemCallback<String>() {
override fun areItemsTheSame(oldItem: String, newItem: String): Boolean {
// need a unique identifier to have sure they are the same item. could be a comparison of ids. In this case, that is just a list of strings just compare like this below
return oldItem == newItem
}
override fun areContentsTheSame(oldItem: String, newItem: String): Boolean {
// compare the objects
return oldItem == newItem
}
}
}
}
class MyViewModel: ViewModel() {
private val _rating = MutableLiveData<List<String>>(emptyList())
val rating: LiveData<List<String>>
get() = _rating
// implement a function that adds a new item on the rating list
fun addRating(newRate: String) {
val newList = mutableListOf<String>()
_rating.value?.let { newList.addAll(it) }
newList.add(newRate)
_rating.value = newList
}
}
See that I didn't expose the mutableLiveData, always pay attention to following this best practice to let private the mutableLiveData and let public just the immutable live data.看到我没有公开 mutableLiveData,请始终注意遵循此最佳实践,让 mutableLiveData 私有化,只公开不可变的实时数据。
class MyFragment: Fragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// set the adapter to your recycler view
// observe changes of your live data
viewModel.rating.observe(viewLifecycleOwner) { ratings ->
adapter.submitList(ratings)
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.