Hey!
Coming from the .NET-environment Im am now looking to understand how Dialogs work in Android.
In .NET, when calling MessageBox.Show(...) that creates and shows a popup dialog. In the call to Show I can specify what buttons should be available in the popup, for example:
DialogResult myDialogResult = MessageBox.Show("My text here", "My caption here", MessageBoxButtons.YesNoCancel);
As you can see, the call to Show returns a DialogResult when a button is pressed in the popup, informing me what button was clicked. Note that in .NET, execution is halted at the line where the call to Show(...) is made, so it can return the value when a button is pressed.
If I in the above example press "No" the myDialogResult will be equal to
myDialogResult == DialogResult.No
Since I find the .NET-way of using/creating popups very easy and intuitive, I would like that way of creating popups in Android too.
So, the question is if anyone know how to "halt execution" like with the MessageBox.Show, and then return a value whenever the Button is pressed (and the dialog goes away)?
Regards
EDIT 1: To be a little bit more clear:
I need for the execution to halt and wait until the user has chosen a button to click in the popup. The code that follow the call to show the Dialog is dependent on what button is clicked in the Dialog.
Thats why I cannot use what Erich and Alex suggest, since writing code in the onClick-methods as suggested below is not gonna work. The reason is that I cannot continue the "normal execution". Let me take an example:
Let me take an example:
int nextStep = 0; // this variable will not be reached from within the onClick-methods
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Hello!")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
nextStep = 1; // *** COMPILER ERROR!! ***
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
nextStep = 2; // *** COMPILER ERROR!! ***
}
})
.create().show();
if (nextStep == 1)
{
// then do some damage
}
else if (nextStep == 2
// dont do damage
If I wanted the execution to be dependent on the choice in the popup, I would somehow have to make all the variables in the "normal execution" (in this case nextStep) available in the onClick-methods, and that sounds like hell to me.
EDIT 2:
Another obvious example would be a popup asking "Do you want to continue" with the options "Yes" and "No".
If the user presses "Yes", the whole method should be aborted otherwise it should continue execution. How do you solve that nicely?
Regards