問題描述
當用戶輸入 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 上的多個觸發器?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!