'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 1:[1]
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()
}
}
Solution 2:[2]
You just have to invoke method setCanceledOnTouchOutside(), as below:
dialog.setCanceledOnTouchOutside(false);
Happy coding!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | iknow |
Solution 2 | HaroldSer |