Reputation: 8854
I've found solutions on cancelling the dismissing of an AlertDialog when a button of the dialog is touched or a key pressed on the keyboard. However, I only want to cancel the dismissing if a key has been pressed, touching the buttons should still work.
E.g., how to keep an AlertDialog open if a key has been pressed, but keep the button touching functional?
Since I'm using Xamarin, here's my C# code so far, but real Java solutions are accepted too since they're easy to translate:
Building the dialog:
AlertDialog dialog = new AlertDialog.Builder(this)
.SetTitle("blabla")
.SetMessage("more bla")
.SetPositiveButton("OK", (sender2, e2) => {
// Do something
SetResult(Result.Ok, oIntent);
Finish(); })
.SetNegativeButton("Cancel", (sender2, e2) => { })
.Create();
dialog.SetOnShowListener(new AlertDialogShowListener(dialog));
dialog.Show();
And the implementation of the interfaces:
private class AlertDialogShowListener : Java.Lang.Object, IDialogInterfaceOnShowListener {
private AlertDialog _dialog;
internal AlertDialogShowListener(AlertDialog dialog) {
_dialog = dialog;
}
public void OnShow(IDialogInterface dialog) {
Button b = dialog.GetButton((int)DialogButtonType.Positive);
b.SetOnClickListener(new ButtonOnClickListener());
b = dialog.GetButton((int)DialogButtonType.Negative);
b.SetOnClickListener(new ButtonOnClickListener());
}
}
private class ButtonOnClickListener : Java.Lang.Object, View.IOnClickListener {
public void OnClick(View v) {
// How to NOT dismiss if a _key_ has been pressed?
}
}
(PS: I know there's an easier way to write code like this in Xamarin by attaching the Click event, but I thought it's easier for Java professionals to follow it this way with the OnShow and OnClick listeners.)
Upvotes: 2
Views: 1775
Reputation: 8854
I found the answer!
After showing the alert dialog, get the buttons and override their onKeyPress method, so these don't call dismiss on the alert dialog.
In C# it looks like this:
AlertDialog dialog = new AlertDialog.Builder(this)
.SetTitle("blabla")
.SetMessage("blablabla")
.SetPositiveButton("OK", (sender, e) => {
SetResult(Result.Ok, oIntent);
Finish();
})
.SetNegativeButton("Cancel", (sender, e) => { })
.Show(); // Important, or GetButton() will return null
// Now disable the default dismissing actions on key presses.
dialog.GetButton((int)DialogButtonType.Positive).KeyPress += (sender, e) => { };
dialog.GetButton((int)DialogButtonType.Negative).KeyPress += (sender, e) => { };
Upvotes: 2