How to avoid multiple triggers on EditText while user is typing?

女生的网名这么多〃 提交于 2019-11-30 00:11:06
apoorv020

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

One solution would be to not execute your triggered search immediately but after some interval, say 100ms, has passed since the onTextChanged method gets called. Additionally reset this interval each time text is typed.

This way the triggered search doesn't get called while the user is typing.

To wait in the listener before calling triggerSearch; test the length of Editable s.

if(s.length() > THRESHOLD)

If you don't want to trigger the search on every button pressed, then you need to know when the user is done. I would avoid complex ideas of attempting to figure out when the user is done typing. It will lead to the user being confused as to when the search occurs.

Simple answer then is put a "done" button and apply an onClickListener on the button and execute your search there.

Easiest code: in xml

<Button
android:onClick="onDoneClicked"
... the rest of your button layout
/>

in java:

@Override
public void onDoneClicked(View view){
EditText queryView = (EditText) findViewById(R.id.querybox);
triggerSearch(queryView.toString());
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!