How to dismiss a Material Alert Dialog in Kotlin

57 Views Asked by At

I have created this Material Alert Dialog. I want to dismiss it once the record is update or when user click cancel button (btnCancel). I am unable to use dismiss() as it's not available.

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()

    }
1

There are 1 best solutions below

0
Meet Miyani On

You will need to build the dialog first, as I can see you are using MaterialAlertDialogBuilder, so below that you can build the dialog, it should be updateDialog.build() or updateDialog.create() as updateDialog is a DialogBuilder here.

After that, just show

val dialog = updateDialog.build() // or it maybe create()

dialog.show() // <- to show on click

dialog.dismiss() // <- to dismiss on click

This will solve the problem!