【发布时间】:2021-07-31 11:19:06
【问题描述】:
我从片段中打开了警报对话框,它有两个编辑文本和一个按钮,一次可以看到一个编辑文本。单击提交时,调用 API -> 基于响应 -> 第二个编辑文本将可见。我使用 ViewModel 和 LiveData 来监听响应。
问题:如何在警报对话框上下文中正确观察实时数据?
val dialogBinding: DialogTestBinding = DialogTestBinding.inflate(layoutInflater)
val dialog = AlertDialog.Builder(requireContext()).create()
dialogBinding.edtMobile.setText(viewModel.userMobile)
dialogBinding.submit.setOnClickListener {
if (dialogBinding.edtMobile.visibility == View.VISIBLE) {
//observing live data with viewLifecycleOwner - how to correctly manage for alert dialog//
viewModel.newNumber.observe(viewLifecycleOwner) {
dialogBinding.edtOtp.visibility = View.VISIBLE
dialogBinding.edtMobile.visibility = View.GONE
//viewModel.newNumber.removeObservers(viewLifecycleOwner)
}
val newNumber = dialogBinding.edtMobile.text.toString()
callAPI(newNumber, "")
} else {
val newNumber = dialogBinding.edtMobile.text.toString()
val otp = dialogBinding.edtOtp.text.toString()
callAPI(newNumber, otp)
}
}
dialog.setView(dialogBinding.root)
dialog.show()
这是有效的,但即使在 AlertDialog 被解除后,它也会监听更改。除了手动移除 Observer 还有其他选择吗?
【问题讨论】:
标签: android android-alertdialog android-livedata android-viewmodel