during my debug sessions I found a strange thing occurring. I have an EditText
control for which I defined the current activity as OnKeyListener
to perform validation while user types.
Code
txtPhoneNumber.setOnEditorActionListener(this);
txtPhoneNumber.setOnKeyListener(this);
txtPhoneNumber.setOnFocusChangeListener(this);
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
String phoneNumber = ((TextView) v).getText().toString();
if (phoneNumber != null && !"".equals(phoneNumber))
setValidPhoneNumber(checkValidPhoneNumber(phoneNumber));
setForwardButtonEnabled(this.validPhoneNumber && this.readyToGo);
if (actionId == EditorInfo.IME_ACTION_DONE) {
InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
in.hideSoftInputFromWindow(v.getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
return false;
}
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
String phoneNumber = ((TextView) v).getText().toString();
if (phoneNumber != null && !"".equals(phoneNumber))
setValidPhoneNumber(checkValidPhoneNumber(phoneNumber));
setForwardButtonEnabled(this.validPhoneNumber && this.readyToGo);
return false;
}
OK I can admit that this is quite redundant to perform validation again when the user is pressing the Enter key, more than just closing the soft keyboard. However I found that the OnKey event is dispatched twice.
For example I'm writing 3551234567
and I already typed 355
. When I press 1, one event is fired having v.getText()
= 355
and next another event has v.getText()
= 3551
.
I would like to know if this is normal and if this can be avoided by either distinguishing if this is a "preOnKeyEvent" or "postOnKeyEvent". I only need the string after the event, not before.
Thank you