当我点击一个视图时,它会修改在片段中观察到的X。我需要将单击的视图传递给viewmodel。X.observe((方法。我无法设置视图模型。X.observe在OnItemClickListener中,因为它将在每次单击项目时尝试创建新的观察者。将单击的项目传递给viewmodel.observe方法的最佳方式是什么?是否正在创建一个全局变量来保存"仅单击项目"选项?
片段代码:
lateinit var viewClicked: View
val itemClickListener =
(object : OnItemClickListener<View> {
override fun onItemClicked(item: View) {
viewClicked = item
//do something else
}
})
viewModel.signalStatus.observe(viewLifecycleOwner, {
//Is viewClicked global my only option to be able to access here?
// I can't have this observer inside my click listener as it will trigger this multiple times when user clicks on view
if (viewClicked == btnView) {
//do something
}
})
是的,全局变量。或者将它们分组到数组中,改为传递索引。