Search code examples
androiduser-interfaceandroid-alertdialog

How to prevent AlertDialog box getting dismissed when clicked outside the dialog box?


I have an AlertDialog box that I am using to get input from the user. But when the user clicks outside the dialog, it is getting dismissed irrespective of whether the user has entered the input or not.

That input is very crucial for further processes in the app. So I've to keep it.
I would really appreciate a different approach as long as it fulfills my purpose.


Solution

  • Here is a simple dialog which cannot be canceled by clicking outside it:

    class MainActivity : AppCompatActivity()
    {
        override fun onCreate(savedInstanceState: Bundle?)
        {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            // create dialog
            val builder = AlertDialog.Builder(this).apply {
    
                setPositiveButton("Ok",
                                  DialogInterface.OnClickListener { dialog, id ->
                                      // User clicked OK button
                                  })
    
            }
    
            //This will make dialog unCancelable
            val alertDialog: AlertDialog = builder.setCancelable(false).create()
    
            // show dialog
            alertDialog.show()
        }
    }