我创建了这个材料警报对话框。我想在记录更新后或用户单击取消按钮(btnCancel)时关闭它。我无法使用解雇(),因为它不可用。
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)
}
}
}
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()
//TODO dismiss dialog
}
}else{
Toast.makeText(applicationContext, "Please enter name and email", Toast.LENGTH_SHORT).show()
}
}
binding.btnCancel.setOnClickListener {
//TODO dismiss dialog
}
updateDialog.show()
}
您需要首先构建对话框,因为我可以看到您正在使用
MaterialAlertDialogBuilder
,因此在下面您可以构建对话框,它应该是updateDialog.build()
或updateDialog.create()
,因为updateDialog
是一个DialogBuilder 这里。
之后,只需展示
val dialog = updateDialog.build() // or it maybe create()
dialog.show() // <- to show on click
dialog.dismiss() // <- to dismiss on click
这样问题就解决了!