AlertDialog Input with validation

DelwarDelwar USMember ✭✭

Last few days I've been browsing for a good sample code about AlertDialog for input. I came across large code using inflator and layout which unnecessarily involves too many Activity and Layout. Here is a simple AlertDialog with input, input validation, Positive Button Validation. You may ignore the Task.Delay or improve the code to make the call awaitable. This is a method in a class so you can call it anywhere in the application for re-usability.

--------------- Code----------------------

EditText et = new EditText(this.context);

            et.InputType = Android.Text.InputTypes.NumberFlagDecimal | Android.Text.InputTypes.ClassNumber;

            AlertDialog.Builder builder = new AlertDialog.Builder(this.context);
            builder.SetTitle("Enter Quantity");
            builder.SetPositiveButton("OK", delegate
                if (!string.IsNullOrEmpty(et.Text))
                    this.Number = et.Text;
            builder.SetNegativeButton("CANCEL", delegate { builder.Dispose(); });
            var alertdialog = builder.Create();


            alertdialog.GetButton((int)DialogButtonType.Positive).Enabled = false;

            et.AfterTextChanged += (sender, e) =>
                      alertdialog.GetButton((int)DialogButtonType.Positive).Enabled = true;

            while (string.IsNullOrEmpty(this.Number))
                await Task.Delay(25);

            return this.Number;

        catch(Exception ex)
            return ex.Message;


  • carlosancarlosan Member ✭✭

    Hello and thank you! In the line EditText et = new EditText(this.context) I changed "this.content" by "this" and works!


Sign In or Register to comment.