hungariandude
hungariandude

Reputation: 386

Close dialog, when pressed OK button on it

If the user clicks on a button, a dialog shows up, asking to input a string, and there's an 'OK' button on the same dialog, when the user presses that, the dialog should close. That's at least the plan, the problem is: after adding the eventhandler to the OK button, my application freezes, when the user would open the dialog.

addNewFamButton = FindViewById<Button>(Resource.Id.newFamilyButton);
addNewFamButton.Click += (sender, e) => {
    Dialog dialog = new Dialog(this);
    dialog.SetContentView(Resource.Layout.addNewFamily);
    dialog.SetTitle("Add new family to the list");
    dialog.Show();

    // Problem starts here:
    Button saveNewFamily = FindViewById<Button>(Resource.Id.dialogButtonOK);
    saveNewFamily.Click += (object o, EventArgs ea) => { dialog.Dispose(); };                
};

I tried it with dialog.Cancel() too, but I got the same results. If I remove the last two lines, the dialog works, but obviously won't close.

FIXED: Thanks to user370305 for the simple solution:

Button saveNewFamily = dialog.FindViewById<Button>(Resource.Id.dialogButtonOK);

Upvotes: 2

Views: 2900

Answers (2)

Ibukun Muyide
Ibukun Muyide

Reputation: 1298

try this

        // create an EditText for the dialog
        final EditText enteredText = new EditText(this);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Title of the dialog");
        builder.setView(enteredText);
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int id)
            {
               // perform any operation you want
                enteredText.getText().toString());// get the text

              // other operations
                dialog.cancel();  // close the dialog

            }
        });
        builder.create().show();

Upvotes: 2

user370305
user370305

Reputation: 109237

Your OK button is part of Dialog view, so you have to find that view using your dialog object reference, something like, (I am not familiar with xamarin but this one gives you hint)

Change your line,

// Problem starts here:
Button saveNewFamily = FindViewById<Button>(Resource.Id.dialogButtonOK);

with

Button saveNewFamily = dialog.FindViewById<Button>(Resource.Id.dialogButtonOK);

Upvotes: 2

Related Questions