如何在Kotlin中关闭Material Alert Dialog?更新/取消时无法调用dismiss()
解决方案
问题出在你当前的updateDialog是MaterialAlertDialogBuilder实例,而非最终显示的Dialog对象,Builder本身没有dismiss()方法。你需要保存show()方法返回的Dialog实例,才能调用关闭方法。
修改步骤:
- 调用
updateDialog.show()时,将返回的Dialog对象赋值给一个变量,比如val dialog = updateDialog.show() - 在需要关闭对话框的位置,调用这个变量的
dismiss()方法
修改后的完整代码:
private fun updateRecordDialog(id: Int, employeeDao: EmployeeDao){ val updateDialog = MaterialAlertDialogBuilder(this, R.style.Theme_Dialog) val binding = DialogUpdateBinding.inflate(layoutInflater) updateDialog.setView(binding.root) lifecycleScope.launch { employeeDao.fetchEmployeeById(id).collect{ if (it != null){ binding.etUpdateName.setText(it.name) binding.etUpdateEmailId.setText(it.email) } } } // 保存Dialog实例 val dialog = updateDialog.show() binding.btnUpdate.setOnClickListener { val updatedName = binding.etUpdateName.text.toString() val updatedEmail = binding.etUpdateEmailId.text.toString() if (updatedName.isNotEmpty() && updatedEmail.isNotEmpty()){ lifecycleScope.launch { employeeDao.update(EmployeeEntity(id = id, name = updatedName, email = updatedEmail)) Toast.makeText(applicationContext, "Record updated", Toast.LENGTH_SHORT).show() // 关闭对话框 dialog.dismiss() } }else{ Toast.makeText(applicationContext, "Please enter name and email", Toast.LENGTH_SHORT).show() } } binding.btnCancel.setOnClickListener { // 关闭对话框 dialog.dismiss() } }
注意:如果Dialog需要在协程异步逻辑完成后关闭,确保dialog变量在协程作用域内可访问(上述代码中变量定义在函数顶层,可直接调用)。
内容的提问来源于stack exchange,提问作者Abdul Lateef Sherani
相关产品推荐
相关产品推荐

