Android 如何从MutableLiveData获取元素
首先,我将给出一个代码示例,并在下面描述问题 MainViewModelAndroid 如何从MutableLiveData获取元素,android,kotlin,adapter,android-livedata,Android,Kotlin,Adapter,Android Livedata,首先,我将给出一个代码示例,并在下面描述问题 MainViewModel class MainViewModel @ViewModelInject constructor(private val ordersRepository: OrdersRepository) : ViewModel() { private val _orderList = MutableLiveData<State<List<Order>>>() va
class MainViewModel @ViewModelInject constructor(private val ordersRepository: OrdersRepository) :
ViewModel() {
private val _orderList = MutableLiveData<State<List<Order>>>()
val orderList: LiveData<State<List<Order>>>
get() = _orderList
fun getOrders() {
viewModelScope.launch {
ordersRepository.getAllOrders().collect {
Log.d("test2",it.toString())
_orderList.value = it
}
}
}
}
现在我拿不到它的目标了
更新有错误的v2
向适配器的类型列表构造函数添加一个参数,该类型列表是要填充RecyclerView的初始列表。submitList是一种方法,当在适配器的生命周期中,您希望向适配器发送更新的列表时,将调用该方法。(当列表更改时说) 当您在
initOrders()
中收到列表时,执行当前正在执行的操作,即
(recycler.adapter as? HomeItemAdapter)?.submitList(state.data.toMutableList())
使用这个片段
inner class YouViewHolder(val view: View) : RecyclerView.ViewHolder(view) {
private val title: TextView = view.findViewById(R.id.product_name)
private val count: TextView = view.findViewById(R.id.product_count)
private val price: TextView = view.findViewById(R.id.product_price)
fun bind(pos: Int) {
title.text = mOrders?.get(pos)?.name
price.text = mOrders?.get(pos)?.price
count.text = pos.toString()
}
}
你的答案很有用,我很高兴你留下了它,但你没有留下主要问题的答案。我的问题是我不能绑定对象。因为我以前从列表中获取它,并且可以执行私有变量title:TextView=view。findViewById(R.id.item_title)title=列表产品[位置]。标题,现在我无法得到它的对象!bind()函数中的title.text=mOrders?.get(position).data.toString()您在DiffCallback类中编写的代码有错误,我无法修复它(错误是什么?请尝试从同一函数中删除.id访问权限)
class HomeItemDiffCallback(
private val oldList: List<Order>,
private val newList: List<Order>
) : DiffUtil.ItemCallback() {
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldList[oldItemPosition].id == newList[newItemPosition].id
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldList.get(oldItemPosition).equals(newList.get(newItemPosition));
}
}
recycler.adapter = HomeItemAdapter(mViewModel, null)
(recycler.adapter as? HomeItemAdapter)?.submitList(state.data.toMutableList())
inner class YouViewHolder(val view: View) : RecyclerView.ViewHolder(view) {
private val title: TextView = view.findViewById(R.id.product_name)
private val count: TextView = view.findViewById(R.id.product_count)
private val price: TextView = view.findViewById(R.id.product_price)
fun bind(pos: Int) {
title.text = mOrders?.get(pos)?.name
price.text = mOrders?.get(pos)?.price
count.text = pos.toString()
}
}