如何使TextWatcher等待一段时间才能执行某些操作 [英] How to make TextWatcher wait for some time before doing some action
问题描述
我有一个EditText
来过滤其下面的ListView
中的项目,通常可能包含1000多个项目. TextWatcher
是:
I have an EditText
to filter the items in the ListView
below it, which may contain more than 1000 items usually. The TextWatcher
is:
txt_itemSearch.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
fillItemList();
}
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
});
这里的问题是,用户键入每个字母后,列表将被刷新,而正是由于重复的列表更新导致UI变慢.
The issue here is that with each letter typed by the user, the list is getting refreshed and it's this repeated list update which causes the UI to be slow.
如何使TextWatcher
等待1-2秒,如果2秒后没有更多输入,请过滤列表.有什么建议吗?
How can I make the TextWatcher
wait for 1-2 secs and if no more input happens after 2 secs, then filter the list. Any suggestions guys?
推荐答案
如何让textWatcher等待1-2秒,如果没有更多输入 会在2秒后发生,然后过滤列表.
How can I make the textWatcher wait for 1-2 secs and if no more input happens after 2 secs, then filter the list.
正如我在评论中已经说过的那样,您应该使用适配器的getFilter()
方法进行研究.因为这可能不合适(如您所说),请尝试实现适配器的过滤器用来在过滤器输入之间进行抵消的相同机制.
As I already said in the comment you should look into using the getFilter()
method of the adapter. As that may not be suitable(as you say) try to implement the same mechanism the adapter's filter uses to cancel in between filter inputs.
private Handler mHandler = new Handler();
public void afterTextChanged(Editable s) {
mHandler.removeCallbacks(mFilterTask);
mHandler.postDelayed(mFilterTask, 2000);
}
其中filterTask
是:
Runnable mFilterTask = new Runnable() {
@Override
public void run() {
fillItemList();
}
}
这篇关于如何使TextWatcher等待一段时间才能执行某些操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!