我希望在启动APP时打开密码输入对话框。
如果输入正确的密码,对话框将关闭并显示主UI。
如果输入错误密码,对话框将保持打开状态并再次需要用户输入。
我该怎么办?谢谢!
目前,无论我输入正确密码还是错误密码,对话框始终处于关闭状态。
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()
}
答案 0 :(得分:2)
如果你在alertDialog.onShowlistener里面处理了onclick监听器,那么你可以避免对话关闭流程。请在下面找到修改后的代码。
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()
}
参考:How to prevent a dialog from closing when a button is clicked