如何解决如何观察警报对话框的实时数据
我从片段打开了警报对话框,它有两个编辑文本和一个按钮,一次可以看到一个编辑文本。单击提交时,调用 API -> 基于响应 -> 第二个编辑文本将可见。我使用 ViewModel 和 LiveData 来监听响应。
问题:如何在 Alert Dialog 上下文中正确观察实时数据?
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 被解除后,它也会监听更改。除了手动移除观察者之外,还有其他选择吗?
解决方法
要在 Dialog
中构建复杂的逻辑,请使用 DialogFragment
。而对应的 ViewModel
负责存储 LiveData
。
class IpAddressEditorDialog : DialogFragment() {
private lateinit var binding: DialogIpAddressEditorBinding
private lateinit var viewModel: IpAddressEditorViewModel
private lateinit var alertDialog: AlertDialog
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
binding = DataBindingUtil.inflate(layoutInflater,R.layout.dialog_ip_address_editor,null,false)
viewModel = ViewModelProvider(this).get(IpAddressEditorViewModel::class.java)
alertDialog = getAlertDialog()
binding.viewModel = viewModel
binding.lifecycleOwner = this
return alertDialog
}
private fun getAlertDialog(): AlertDialog {
val dialogBuilder = MaterialAlertDialogBuilder(requireContext()).apply {
setView(binding.root)
setPositiveButton(R.string.confirm_label) {
//do your stuff
}
setNegativeButton(R.string.cancel_label) {
//do your stuff
}
}
return dialogBuilder.create()
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。