有另一个程序员编写的项目。里面有这样的代码
class CardsViewModel : ViewModel() {
val selected = MutableLiveData<PaymentCard>()
companion object {
@JvmStatic
var keyId = 0
}
}
每次向 ViewModel 添加一些数据时,此 keyId 都会递增:
val cardsViewModel = ViewModelProviders.of(requireActivity())
.get(CardsViewModel.keyId.toString(), CardsViewModel::class.java)
CardsViewModel.keyId++
cardsViewModel.selected.value = PaymentCard.EMPTY
然后以这种方式得到它:
val cardsViewModel = ViewModelProviders.of(requireActivity()).get(CardsViewModel.keyId.toString(), CardsViewModel::class.java)
bindingId = cardsViewModel.selected.value?.bindingId ?: ""
我最近才开始学习 LiveData,我不清楚这个 id 提供了什么以及如何使用它?我的印象是我将数据绑定到某个键,然后使用该键检索它 =) 但这会引起很多问题。
PS 项目写的不好,所以可能这是某种拐杖,但是由于缺乏LiveData的经验,我无法理解这个