3

I have a custom search activity that serves search suggestions. I get a reference to the search input box and set a handler:

mSearchInput = FindViewById(Resource.Id.searchBoxInput) as EditText;
mSearchInput.KeyPress += new System.EventHandler<View.KeyEventArgs>(OnSearchKeypress);

This is the handler that should be called on every key press:

private void OnSearchKeypress(object sender, View.KeyEventArgs e) {
    string query = mSearchInput.Text;
    if (e.KeyCode == Keycode.Enter && !string.IsNullOrEmpty(query)) {
        e.Handled = true;
        // launch search results activity
    }
    else {
        e.Handled = false;
        if (query.Length > 2) {
            // load suggestions if we have 2+ characters
        }
    }
}

For some reason, on the soft keyboard, only certain key presses fire the event at all. Enter and Delete fire the event. Alphanumeric keys do not. Even if I take out all of the logic and simply do a Toast with e.KeyCode.ToString() it only shows the toast on those few keys.

Am I listening for the wrong event, is this a bug, or have I made some other mistake?

Device: Droid X2 Mono Version: 4.0.4

Update: I discovered that KeyPress is triggered twice for each physical press of a key: once for KeyEventActions.Up and once for Down. This doesn't explain why only certain keys fire the event but it should be noted that you need to check event.E.Action to find out whether the press or release is currently triggering the event.

profexorgeek
  • 1,190
  • 11
  • 21

1 Answers1

0

When is the event not firing? If it is when the user is typing, then you can use the TextChanged event. You can then continue with your implementation in the OnKey method.

Also, look at this article for the "search" button:

http://www.stackoverflow.com/questions/1489852/android-handle-enter-in-an-edittext

Matthew
  • 4,832
  • 2
  • 29
  • 55
  • Also, an EditText is also a TextView, so you can have a look around there. – Matthew Feb 29 '12 at 22:22
  • 1
    The event only fires if you press delete, enter and the hardware back button. TextChanged does work but it seems like a bug that the KeyPress event only fires on a few select keys. Implementing two listeners to handle it seems like bad pattern. – profexorgeek Mar 01 '12 at 23:14