我必须在用户停止输入后运行一次函数但我的函数多次运行

时间:2016-12-01 05:23:29

标签: android android-edittext

我必须在用户停止输入后只运行一次功能,但我的功能会多次运行。我检测到用户何时停止输入但无法执行我的功能一次。

@Override
public void onTextChanged(CharSequence charSequence, final int i, final   
    int i1, final int i2) {   
    Timer timer = new Timer();
    //Run after user stops typing
    TimerTask tt = new TimerTask() {
      @Override
      public void run() {
        Date myRunTime = new Date();
        if ((lastTypeTime.getTime() + 1000) <= myRunTime.getTime()) {
          Handler h = new Handler(Looper.getMainLooper());
          h.post(new Runnable() {
          @Override
          public void run() {
            Log.i("t_type", "Type Finish");
            //Issue : This is printed multiple time.
          }
        });
      } else {
        Log.i("t_cancel", "cancel");//cancel
      }
    }
  };
  timer.schedule(tt, 2000);//two second delay after user stops typing
}

2 个答案:

答案 0 :(得分:1)

我以这种方式解决了这个问题。谢谢@jitesh mohite

  @Override
public void afterTextChanged(Editable editable) {
    Log.i("t_text", editable.toString());
    if (!isTyping) {
        isTyping = true;
        Log.i("t_type", "Typing");
    }
    timer.cancel();
    timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            android.os.Handler handler = new 

android.os.Handler(Looper.getMainLooper());
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Log.i("t_type", "Type Finish");
                    Toast.makeText(SearchActivity.this, "Type Finish", 

Toast.LENGTH_LONG).show();
                    isTyping = false;
                }
            });
        }
    }, 2000);
}

答案 1 :(得分:0)

这就是我为我所做的工作!

long delay = 1000; // 1 seconds after user stops typing
long last_text_edit = 0;
Handler handler = new Handler();

private Runnable input_finish_checker = new Runnable() {
    public void run() {
        if (System.currentTimeMillis() > (last_text_edit + delay - 500)) {
            // TODO: do what you need here
            // ............
            // ............
            DoStaff();
        }
    }
};

EditText editText = (EditText) findViewById(R.id.editTextStopId);
editText.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged (CharSequence s,int start, int count, int after){

    }
    @Override
    public void onTextChanged ( final CharSequence s, int start, int before, int count){
        //You need to remove this to run only once
        handler.removeCallbacks(input_finish_checker);

    }
    @Override
    public void afterTextChanged ( final Editable s){
        //avoid triggering event when text is empty
        if (s.length() > 0) {
            last_text_edit = System.currentTimeMillis();
            handler.postDelayed(input_finish_checker, delay);
        } else {

        }
    }
  }

);