简体   繁体   中英

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.

You just have to invoke method setCanceledOnTouchOutside(), as below:

dialog.setCanceledOnTouchOutside(false);

Happy coding!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM