How can I do something, 0.5 second after text changed in my EditText?

前端 未结 14 1222
渐次进展
渐次进展 2020-12-23 08:49

I am filtering my list using an EditText. I want to filter the list 0.5 second after user has finished typing in EditText. I used the afterTextChanged

14条回答
  •  误落风尘
    2020-12-23 09:32

    editText.addTextChangedListener(
        new TextWatcher() {
            @Override public void onTextChanged(CharSequence s, int start, int before, int count) { }
            @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
    
            private Timer timer=new Timer();
            private final long DELAY = 1000; // milliseconds
    
            @Override
            public void afterTextChanged(final Editable s) {
                timer.cancel();
                timer = new Timer();
                timer.schedule(
                    new TimerTask() {
                        @Override
                        public void run() {
                            // TODO: do what you need here (refresh list)
                            // you will probably need to use runOnUiThread(Runnable action) for some specific actions (e.g. manipulating views)
                        }
                    }, 
                    DELAY
                );
            }
        }
    );
    

    The trick is in canceling and re-scheduling Timer each time, when text in EditText gets changed. Good luck!

    UPDATE For those interested in how long to set the delay, see this post.

提交回复
热议问题