我有一个textWatcher来检测搜索栏中的文本变化。一旦发生文本更改,它将立即执行搜索操作。
例如,当我在搜索栏中键入"a“时,它将在For循环中运行itemData.name.toLowerCase().contains("a");
,以搜索名称包括"a”的项,并将其显示在循环视图中。
然后我继续输入"b",它将再次在for循环中运行itemData.name.toLowerCase().contains("ab");
,以搜索名称包括"ab“的项。
这就是我的想法
//this will run when text change occur
for(){//for all item of itemlist
if(){//if item name contains the text
//store this item in itemlist
}
}
//update new itemlist to recycle view here
然而,表演却非常缓慢。当我输入搜索栏时,它会有一些滞后。有人能解决这个问题吗?
发布于 2018-03-12 00:40:36
在自动完成过程中,您希望每次击键都会对结果进行过滤。相反,您希望在完成键入之后触发搜索。如果用户没有完成键入他的关键字,我们将执行一个搜索请求与每一个键键入。
为了避免如此多的请求并优化搜索体验,您可以为搜索字段TextWatcher
使用EditText
。
private EditText searchText;
private TextView resultText;
private Timer timer;
private TextWatcher searchTextWatcher = new TextWatcher() {
@Override
public void afterTextChanged(Editable arg0) {
// user typed: start the timer
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
// do your actual work here
}
}, 600); // 600ms delay before the timer executes the „run“ method from TimerTask
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// nothing to do here
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// user is typing: reset already started timer (if existing)
if (timer != null) {
timer.cancel();
}
}
};
这段代码片段只是向您展示了解决问题的示例用例,即如何猜测用户何时完成输入,并希望在没有提交按钮的情况下启动搜索。我们使用600毫秒的延迟开始搜索。如果用户在搜索字段中键入另一个字母,我们会重置计时器,然后再等待600 ms。
https://stackoverflow.com/questions/49230819
复制