我想从Recyclerview Adapter调用ViewModel.delete(房间数据库(方法,但它不起作用。有什么想法吗?
我想在OnBindViewHolder中调用ViewModel,如下所示:holder.binding.ivItemWalletDelete.setOnClickListener{WalletViewModel。。。}
但我得到了错误:在一个空对象上
RecyclerView适配器(WalletListAdapter.kt(
class WalletListAdapter:
ListAdapter<Wallet, WalletListAdapter.ViewHolder>(WalletDiffCallback()){
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): ViewHolder {
return ViewHolder.from(parent)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = getItem(position)
holder.bind(item)
}
class ViewHolder private constructor(val binding: ItemWalletsBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(item: Wallet) {
binding.wallet = item
binding.executePendingBindings()
}
companion object {
fun from(parent: ViewGroup): ViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val binding = ItemWalletsBinding.inflate(layoutInflater, parent, false)
return ViewHolder(binding)
}
}
}
}
class WalletDiffCallback : DiffUtil.ItemCallback<Wallet>() {
override fun areItemsTheSame(oldItem: Wallet, newItem: Wallet): Boolean {
return oldItem.walletId == newItem.walletId
}
override fun areContentsTheSame(oldItem: Wallet, newItem: Wallet): Boolean {
return oldItem == newItem
}
}
ViewModel(WalletViewModel.kt(
class WalletViewModel(application: Application): AndroidViewModel(application) {
private val repository = WalletRepository(application)
private val liveWalletList = repository.getLiveDataWallets()
fun insert(wallet: Wallet){
viewModelScope.launch {
repository.insert(wallet)
}
}
fun update(wallet: Wallet){
viewModelScope.launch {
repository.update(wallet)
}
}
fun delete(wallet: Wallet){
viewModelScope.launch {
repository.delete(wallet)
}
}
fun getWalletById(walletId: Long): Wallet? {
var wallet: Wallet? = null
viewModelScope.launch {
wallet = repository.getWalletById(walletId)
}
return wallet
}
fun getAllWallets(): List<Wallet>? {
var wallets: List<Wallet>? = null
viewModelScope.launch {
wallets = repository.getAllWallets()
}
return wallets
}
fun getLiveWalletList(): LiveData<List<Wallet>> = liveWalletList
}
解决这类问题的一种常见方法是创建一个将传递到适配器的回调。
在WalletListAdapter
类中,传入一个接受Wallet
对象的回调。
class WalletListAdapter(private val onDeleteCallback: (Wallet) -> Unit) {}
在ViewHolder
中,您可以在每个回收器视图项上设置一个OnClickListener
,并将Wallet
对象传递给回调函数。看起来像这样:
binding.root.setOnClickListener { onDeleteCallback(item) }
最后,初始化WalletListAdapter
的视图(活动、片段等(将传入一个接受Wallet
对象的函数。然后在这里调用WalletViewModel
的delete函数。
class WalletListActivity: Activity() {
@Inject
lateinit var viewModel: WalletViewModel
override fun onCreate(bundle: Bundle?) {
super.onCreate(savedInstanceState)
// initialize the WalletListAdapter and pass in the callback
val adapter = WalletListAdapter(::deleteWallet)
}
private fun deleteWallet(wallet: Wallet) {
viewModel.delete(wallet)
}
}
注意:您可以先用一个空构造函数初始化WalletListAdapter
类,然后创建一个方法将回调函数从视图传递给WalletListAdapter
类。重点是";传播";单击事件从适配器返回到视图,因此视图可以调用viewmodel的方法。