我有一个自动完成的edittext字段,每次文本更改时都会向服务器发送查询,但是,如果用户键入大量文本然后按下“删除”,我不想为每个删除的字符发送查询。解决此问题的一种方法是在输入字符时缓存所有查询,然后在删除时回放缓存-但在我看来,这不必要地复杂。一种更简单的方法是检测按下/按下键,然后仅在文本已更改但用户也没有触摸键盘的情况下发送查询。这使我面临如何从软键盘捕获键盘输入的困难。
我已经尝试过ontouchlistener(不触发)和onkeypressedlistener(也不触发),甚至覆盖edittext中的onKeyPreIme(也不触发)。有没有办法做到这一点?
我的最终解决方案是将Andrea的答案与Jelle的答案相结合。我记录了上一次在textwatcher中按下某个键的时间,然后仅在此之后500毫秒对它进行测试-为了确定这是最后一次按下的键:
private static long lastCharacterPress = 0l;
private Editable stringToSearchFor;
private Handler delayedCharacterCheck;
edittext.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
lastCharacterPress = System.currentTimeMillis();
stringToSearchFor = s;
if (s.length() > 2) {
delayedCharacterCheck.postDelayed(new Runnable() {
@Override
public void run() {
checkIfTimeHasPassed();
}
}, 500);
} else ...
}
});
然后我把这种方法:
private void checkIfTimeHasPassed() {
if (!TextUtils.isEmpty(stringToSearchFor) && edittext.getText().length() > 2 && System.currentTimeMillis() - lastCharacterPress > 499) {
// perform the actual query
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句