We’re still working on an Android version of our fantastic 10bii Cash Calculator, but it has been frustrating at times. I’m posting this with the hope that someone else who runs into this problem will be able to find an answer with less pain.

Warning: Geeky Content!

We wanted to capture what a user was typing into an EditText (a text field). The Android Developer Guide Tutorial on EditText says to create a View.OnKeyListener() and attach it to the EditText. However, that View.OnKeyListener does NOT deliver all of the key events on virtual and physical keyboards, nor does it behave consistently from emulator to device.

SOLUTION: TextWatcher

You can create a TextWatcher object which will receive simple events every time the text in an EditText changes. It’s just that simple and I’m frankly confused as to why the Android Developer documentation sent us on a frustrating wild goose chase. Here is some example code of how to handle these events:

final MyDataObject data = getMyDataObject();

EditText editText = (EditText)convertView.findViewById(R.id.myEditText);
editText.setText(data.getMyText());
editText.addTextChangedListener(new TextWatcher() {

public void afterTextChanged(Editable s) {
data.setMyText(s.toString());
}

public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// intentionally left blank
}

public void onTextChanged(CharSequence s, int start, int before, int count) {
// intentionally left blank
}

});

Handling EditText Key Events and Changes

Leave a Reply

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