Android: Pre-Built Dialogs and Event Handling

Using Android’s pre-built dialogs can sometimes be a challenge. The technique shown below may help solve many pre-built dialog related difficulties.

For this example I am using the NumberPicker dialog. The question here is how to handle the event fired by the Done button in the number pad when using a NumberPicker. The NumberPicker itself only sends two events that I can see, OnValueChanged and OnScroll. OnValueChanged only fires when the user presses the up or down buttons to increment/decrement the number. If you want to catch events that occur otherwise, like the Done button being pressed or new numbers being entered via the number pad, you have to get to the EditText view that is the view in the NumberPicker (a view group) and assign the listeners to that view. Doing this is pretty straightforward. Just loop through the views in the NumberPicker until you find the EditText view and then assign the event handlers to that view.

for (int i = 0; i < numberPicker.ChildCount; i++)
{
    var v = numberPicker.GetChildAt(i);
    if (v.GetType() == typeof(EditText)) {
        var editText = v as EditText;
        editText.AfterTextChanged += (object sender, Android.Text.AfterTextChangedEventArgs e) = {
            // Do stuff to handle the user 
            // having pressed a digit on the number pad.
            Console.WriteLine("Text Changed, new value: {0}", editText.Text);
        };
        editText.EditorAction += (object sender, TextView.EditorActionEventArgs e) = {
            // Do stuff to handle the Done button being pressed
            Console.WriteLine("Done pressed, value: {0}", editText.Text);
        };
        break;
    }
}

I hope this saves someone some time.
Aloha!

Leave a Reply

Your email address will not be published. Required fields are marked *