Reputation: 2305
I hope to a password input dialog box is opened when I start an APP.
If I input the correct password, the dialog will close and display main UI.
If I input the error password, the dialog will keep open and require a user input again.
How can I do it? Thanks!
At present, the dialog is always closed no matter I input correct or error password.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.layout_main)
showInputPasswordDialog()
}
private fun showInputPasswordDialog {
val editText = EditText(this)
val inputDialog = AlertDialog.Builder(this)
inputDialog.setTitle("Input")
.setView(editText)
.setCancelable(false)
.setNegativeButton("Cancel", DialogInterface.OnClickListener { dialog, which ->
finish();
})
inputDialog.setPositiveButton("OK",
DialogInterface.OnClickListener { dialog, which ->
val password= editText.text.toString()
if (password=="aa"){
//close the dialog
}else{
toast("Password error")
//Return for input again
}
}).show()
}
Upvotes: 1
Views: 352
Reputation: 1369
If you handle the onclick listener for positive button inside alertDialog.onShowlistener , then you can avoid the dialog closing flow.Please find the modified code below.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.layout_main)
showInputPasswordDialog()
}
private fun showInputPasswordDialog {
val editText = EditText(this)
val inputDialog = AlertDialog.Builder(this)
inputDialog.setTitle("Input")
.setView(editText)
.setCancelable(false)
.setNegativeButton("Cancel", DialogInterface.OnClickListener { dialog, which ->
finish();
})
inputDialog.setPositiveButton("OK",null)
// modified code starts here
val mAlertDialog = inputDialog.create()
mAlertDialog.setOnShowListener(DialogInterface.OnShowListener {
val b = mAlertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
b.setOnClickListener(View.OnClickListener {
val password= editText.text.toString()
if (password=="aa"){
mAlertDialog.dismiss();
//close the dialog
}else{
toast("Password error")
//Return for input again
}
})
})
mAlertDialog.show()
}
ref: How to prevent a dialog from closing when a button is clicked
Upvotes: 2