如何在 Kotlin 中关闭材质警报对话框

问题描述 投票:0回答:1

我创建了这个材料警报对话框。我想在记录更新后或用户单击取消按钮(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()

    }
android kotlin material-design android-alertdialog
1个回答
0
投票

您需要首先构建对话框,因为我可以看到您正在使用

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

这样问题就解决了!

© www.soinside.com 2019 - 2024. All rights reserved.