问题
May i know how to avoid AlertDialog
to close even when i click the OK.
The reason for this is to make a simple error handling when there is a wrong input.
------------------------
Input password
------------------------
Password:______________
_______________________
| OK | | Cancel|
I want this dialog to remain when there is wrong input. so that the user can input again.
My code:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Insert Passcode");
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_TEXT_VARIATION_PASSWORD);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
m_Text = input.getText().toString() ;
if (m_Text.equals(String.valueOf(passcode_value))){
btnAutoLogin.performClick();
}
else
{
xxxxxxxxxxxxxxx
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
回答1:
Yes, you can simply override positive button functionality like this:-
builder.setPositiveButton("OK", null);
AlertDialog dialog = builder.create();
dialog .show();
dialog .getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// implement your code here
});
回答2:
Create the Custom Listener Class First for Button Click Event as follows:
class CustomListener implements View.OnClickListener {
private final Dialog dialog;
public CustomListener(Dialog dialog) {
this.dialog = dialog;
}
@Override
public void onClick(View v) {
// Do whatever you want here
// If tou want to close the dialog, uncomment the line below
//dialog.dismiss();
}
}
And when You are showing the Dialog or initialize the Dialog Button as follows :
AlertDialog dialog = dialogBuilder.create();
dialog.show();
Button button = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
button.setOnClickListener(new CustomListener(dialog));
来源:https://stackoverflow.com/questions/29743416/android-avoid-alertdialog-to-closeerror-handling