安其事件调度两次,当我键入一些文本到文本框。如何prevent? [英] OnKey event dispatched twice when I type some text into a textbox. How to prevent?
问题描述
在我的调试会话,我发现发生了一件怪事。我对我所定义的当前活动为的EditText
控制 OnKeyListener
,同时用户类型进行验证。
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我可以承认,这是一个相当多余的,当用户为pressing回车键,不仅仅是关闭软键盘更再次执行验证。不过,我发现,安其事件分派两次。
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.
例如我写 3551234567
,我已经输入 355
。当我preSS 1,一个触发事件具有 v.getText()
= 355
旁边另一个事件有 v.getText()
= 3551
。
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
.
我想知道这是正常的,如果这可以通过区别,如果这是一个preOnKeyEvent或postOnKeyEvent是可以避免的。我只需要字符串的之后的情况下,没有的前的
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.
感谢您
推荐答案
你可能得到两个键,/键向上事件。
You are probably getting both the key down/key up events.
尝试通过检查该KeyEvent的行动为ACTION_UP行动过滤你的方法。
Try filtering your method by checking the action of the KeyEvent for an ACTION_UP action.
这篇关于安其事件调度两次,当我键入一些文本到文本框。如何prevent?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!