如何避免多个触发器上的EditText,而用户键入? [英] How to avoid multiple triggers on EditText while user is typing?

查看:105
本文介绍了如何避免多个触发器上的EditText,而用户键入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用下面的code进行搜索时,在一个EditText的用户类型:

I use the following code to perform search when user types in an EditText :

EditText queryView = (EditText) findViewById(R.id.querybox);
queryView.addTextChangedListener(new TextWatcher() {
  @Override
  public void afterTextChanged(Editable s) {
    triggerSearch(s.toString()); 
  }
  @Override
  public void beforeTextChanged(CharSequence s, int start, int count, int after) {
  }
  @Override
  public void onTextChanged(CharSequence s, int start, int before, int count) {
  }
});

然而,这将触发多次当用户正在键入一个字。也就是说,如果用户键入你好,这code将触发5次值(H,他,HEL,地狱,你好)。通常情况下,这将是罚款,但触发搜索是昂贵的,我不想浪费在中间的搜索是没有很大的利用资源。我想要么是一个侦听器,用户开始输入后只触发某个阈值,或某种框架,即等待在听者之前调用 triggerSearch ,如果另一事件被触发之前等待,取消本身。

However, this triggers multiple times when the user is typing a word. That is if the user is typing "hello", this code will trigger 5 times with values ("h", "he" , "hel", "hell", "hello"). Normally, this would be fine but the triggered search is expensive and I don't want to waste resources on intermediate searches that are of no great use. What I want is either a listener that triggers only a certain threshold after the user starts typing, or some kind of framework, that waits in the listener before calling triggerSearch, and if another event is triggered before that wait, cancels itself.

推荐答案

由于找不到合适的事件接口,试图触发延迟搜索。在code其实是pretty的简单而强大的。

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

这篇关于如何避免多个触发器上的EditText,而用户键入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆