2

I'm new to Android development and still find myself thinking along C# or C++ lines. I'm hoping you can set me straight here.

I'm trying to implement an AlertDialog with two buttons and have the application do one of two things depending on which button was tapped. All of the examples I've found shows how to do whatever you want done in the OnClickListener. This is good enough if you want to do something very simple like close the application or show a quick Toast message. I want the code in the class from which I called the showDialog(id) to branch off into one of two sections of code based on the button selected in the dialog. How should this be done?

The equivalent C# code that would accomplish this would be something like:

switch (MessageBox.Show("Do you want to continue?", "Error encountered", MessageBoxButtons.YesNo))
{
    case DialogResult.Yes:
        // Do one thing
        break;
    case DialogResult.No:
        // Do another thing
        break;
}
Dewald Swanepoel
  • 1,651
  • 4
  • 15
  • 38
  • You can call a own method, let's call it `onDialogResult(int button)`, and call this method from your `OnClickListener`s. I doubt that a similar pattern to C# is possible, as the method `show` is not blocking, as the UI thread should not get blocked (this would cause serious issues). There's also a [separate question about blocking execution of Dialogs in Android](http://stackoverflow.com/questions/2028697/dialogs-alertdialogs-how-to-block-execution-while-dialog-is-up-net-style) – dst Aug 11 '13 at 15:20
  • Thanks a lot. This is a good answer. Pity you added it as a comment as opposed to an answer because now it seems I can't upvote it. But thanks anyway, it answers my question well. – Dewald Swanepoel Aug 11 '13 at 16:52
  • You're welcome, now added as an answer, too. :) – dst Aug 11 '13 at 17:22

2 Answers2

1

You are looking for AlertDialog here

Volodymyr Lykhonis
  • 2,936
  • 2
  • 17
  • 13
0

You can call a own method, let's call it onDialogResult(int button), and call this method from your OnClickListeners. I doubt that a similar pattern to C# is possible, as the method show is not blocking, as the UI thread should not get blocked (this would cause serious issues).

There's also a separate question about blocking execution of Dialogs in Android.

Community
  • 1
  • 1
dst
  • 3,307
  • 1
  • 20
  • 27