How to make TextWatcher wait for some time before doing some action

别来无恙 提交于 2019-12-20 21:46:11

问题


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) {
}
});

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.

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?


回答1:


How can I make the textWatcher wait for 1-2 secs and if no more input happens after 2 secs, then filter the list.

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);
}

where filterTask is:

Runnable mFilterTask = new Runnable() {

     @Override
     public void run() {
          fillItemList();
     }       
}



回答2:


Using RxBinding :

RxTextView.textChanges(edittext)
            .skipInitialValue()
            .debounce(TIME_TO_WAIT, TimeUnit.MILLISECONDS)
            .subscribe({
               //do the thing
            })
}


来源:https://stackoverflow.com/questions/14660636/how-to-make-textwatcher-wait-for-some-time-before-doing-some-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!