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----------------------

try
{
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(); });
            builder.SetView(et);
            builder.SetCancelable(false);
            var alertdialog = builder.Create();

            alertdialog.Show();

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

            et.AfterTextChanged += (sender, e) =>
              {
                  if(!string.IsNullOrEmpty(et.Text))
                  {
                      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;
        }

Posts

  • carlosancarlosan Member ✭✭

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

    Cheers!

Sign In or Register to comment.