OnKey event dispatched twice when I type some text into a textbox. How to prevent?

 ̄綄美尐妖づ 提交于 2019-12-24 06:31:15

问题


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
    }
 });


来源:https://stackoverflow.com/questions/9864297/onkey-event-dispatched-twice-when-i-type-some-text-into-a-textbox-how-to-preven

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!