How to avoid multiple triggers on EditText while user is typing?(用户打字时如何避免 EditText 上的多个触发器?)
问题描述
当用户输入 EditText 时,我使用以下代码执行搜索:
I use the following code to perform search when user types in an EditText :
EditText queryView = (EditText) findViewById(R.id.querybox);
queryView.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
triggerSearch(s.toString());
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
但是,当用户键入一个单词时,这会触发多次.也就是说,如果用户键入hello",此代码将触发 5 次值(h"、he"、hel"、hell"、hello").通常,这会很好,但触发搜索很昂贵,我不想将资源浪费在没有多大用处的中间搜索上.我想要的是在用户开始键入后仅触发某个阈值的侦听器,或者是某种框架,它在调用 triggerSearch
之前在侦听器中等待,并且如果在该等待之前触发了另一个事件, 自行取消.
However, this triggers multiple times when the user is typing a word. That is if the user is typing "hello", this code will trigger 5 times with values ("h", "he" , "hel", "hell", "hello"). Normally, this would be fine but the triggered search is expensive and I don't want to waste resources on intermediate searches that are of no great use. What I want is either a listener that triggers only a certain threshold after the user starts typing, or some kind of framework, that waits in the listener before calling triggerSearch
, and if another event is triggered before that wait, cancels itself.
推荐答案
由于找不到合适的事件接口,尝试触发延迟搜索.代码实际上非常简单和健壮.
Since couldn't find an appropriate event interface, tried triggering a delayed search. The code is actually pretty simple and robust.
private final int TRIGGER_SERACH = 1;
// Where did 1000 come from? It's arbitrary, since I can't find average android typing speed.
private final long SEARCH_TRIGGER_DELAY_IN_MS = 1000;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == TRIGGER_SERACH) {
triggerSearch();
}
}
};
queryView.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
@Override
public void afterTextChanged(Editable s) {
handler.removeMessages(TRIGGER_SERACH);
handler.sendEmptyMessageDelayed(TRIGGER_SERACH, SEARCH_TRIGGER_DELAY_IN_MS);
});
这篇关于用户打字时如何避免 EditText 上的多个触发器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:用户打字时如何避免 EditText 上的多个触发器?
基础教程推荐
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01