OnKey event dispatched twice when I type some text

2019-07-20 21:52发布

问题:

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

回答1:

You are probably getting both the key down/key up events.

Try filtering your method by checking the action of the KeyEvent for an ACTION_UP action.

Read this for more information



回答2:

You get the event for key down and key up. Its better to listen for text change event instead of key event

txtPhoneNumber.addTextChangedListener(new TextWatcher() {

    public void onTextChanged(CharSequence s, ....){
        //validation
    }
 });