等到用户停止输入后,再在searchview中执行大量搜索 [英] Wait until the user stops typing before executing a heavy search in searchview
问题描述
搜索在我的应用程序中处于中心位置,我需要它能够正常运行.现在我有一个SearchView.我需要内联显示结果,所以我正在使用此代码.
Search is central in my app and I need it to work well. Right now I have a SearchView. I need to display the results inline, so I'm using this code.
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
srl.setVisibility(View.GONE);
return false;
}
@Override
public boolean onQueryTextChange(String query) {
currentQuery = query;
if (query.length()>= 3) {
searchFor(currentQuery);
} else {
srl.setVisibility(View.GONE);
}
return false;
}
});
问题可能很明显.因为我使用的是Firebase,所以我的searchFor()
函数非常繁琐,不需要每个字母都执行它.这不仅破坏了用户体验,而且如果您写下更长的单词,有时甚至会使我的应用程序崩溃.
The problem may be obvious. Because I use firebase, my searchFor()
function is rather heavy and I don't need it to be executed for every single letter. This not only destroys the user experience, it sometimes literally crashes my app if you write down longer words.
我想要的是在用户停止输入时进行搜索.我想我需要有一个将其延迟一秒的处理程序,然后在每次按下字母键并设置一个新的按键时取消该处理程序.从理论上讲,这是有道理的.我只是无法自己将其用于searchView.
What I want is to search when the user stops typing. I guess I need to have a handler that delays it by a second and then cancel that handler everytime a letter key is pressed and set a new one. This theoretically makes sense. I just haven't been able to pull this off myself for a searchView.
我们将不胜感激!
推荐答案
The easiest way to achieve that is RxJava's debounce operator.
结合杰克·沃顿(Jake Wharton)的 RxBinding ,您将得到类似以下的结果:
With combination of Jake Wharton's RxBinding you'll end up with something like this:
RxSearchView.queryTextChanges(searchView)
.debounce(1, TimeUnit.SECONDS) // stream will go down after 1 second inactivity of user
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<CharSequence>() {
@Override
public void accept(@NonNull CharSequence charSequence) throws Exception {
// perform necessary operation with `charSequence`
}
});
这篇关于等到用户停止输入后,再在searchview中执行大量搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!