Xamarin С# - Android - запрет закрытия AlertDialog на клике PositiveButton
Я новичок в Xamarin, и я не знаю, как сделать следующее в С#. Я хочу предотвратить закрытие alertdialog при нажатии на кнопки Positive/Negative. Сначала мне нужно выполнить некоторую проверку на входе. Если вход правильный, диалог может закрыться, иначе я покажу сообщение с инструкциями. В принципе, у меня есть следующий код:
private void CreateAddProjectDialog() {
//some code
var alert = new AlertDialog.Builder (this);
alert.SetTitle ("Create new project");
alert.SetView (layoutProperties);
alert.SetCancelable (false);
alert.SetPositiveButton("Create", HandlePositiveButtonClick);
alert.SetNegativeButton("Cancel", HandelNegativeButtonClick);
}
private void HandlePositiveButtonClick (object sender, EventArgs e) {
//Do some validation here and return false (prevent closing of dialog) if invalid, else close....
}
Теперь я крашу следующую запись в StackOverflow: Как предотвратить закрытие диалогового окна при нажатии кнопки
Я думаю, что код ниже (взятый из потока) имеет решение, но я не знаю, как переписать мой код С# для реализации Java:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Test for preventing dialog close");
builder.setPositiveButton("Test",
new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
//Do nothing here because we override this button later to change the close behaviour.
//However, we still need this because on older versions of Android unless we
//pass a handler the button doesn't get instantiated
}
});
AlertDialog dialog = builder.create();
dialog.show();
//Overriding the handler immediately after show is probably a better approach than OnShowListener as described below
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Boolean wantToCloseDialog = false;
//Do stuff, possibly set wantToCloseDialog to true then...
if(wantToCloseDialog)
dismiss();
//else dialog stays open. Make sure you have an obvious way to close the dialog especially if you set cancellable to false.
}
});
Как закодировать это в С#? Особенно переопределяющая часть в области setPositiveButton...
Ответы
Ответ 1
Для этого нужно немного подумать. Вам нужно будет непосредственно манипулировать объектом AlertDialog
:
// Build the dialog.
var builder = new AlertDialog.Builder(this);
builder.SetTitle("Click me!");
// Create empty event handlers, we will override them manually instead of letting the builder handling the clicks.
builder.SetPositiveButton("Yes", (EventHandler<DialogClickEventArgs>)null);
builder.SetNegativeButton("No", (EventHandler<DialogClickEventArgs>)null);
var dialog = builder.Create();
// Show the dialog. This is important to do before accessing the buttons.
dialog.Show();
// Get the buttons.
var yesBtn = dialog.GetButton((int)DialogButtonType.Positive);
var noBtn = dialog.GetButton((int)DialogButtonType.Negative);
// Assign our handlers.
yesBtn.Click += (sender, args) =>
{
// Don't dismiss dialog.
Console.WriteLine("I am here to stay!");
};
noBtn.Click += (sender, args) =>
{
// Dismiss dialog.
Console.WriteLine("I will dismiss now!");
dialog.Dismiss();
};