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

前端 未结 14 1185
渐次进展
渐次进展 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:21

    Non of the above solution worked for me.

    I needed a way for TextWatcher to not fire on every character I input inside my search view and show some progress, meaning I need to access UI thread.

    private final TextWatcher textWatcherSearchListener = new TextWatcher() {
        final android.os.Handler handler = new android.os.Handler();
        Runnable runnable;
    
        public void onTextChanged(final CharSequence s, int start, final int before, int count) {
            handler.removeCallbacks(runnable);
        }
    
        @Override
        public void afterTextChanged(final Editable s) {
            //show some progress, because you can access UI here
            runnable = new Runnable() {
                @Override
                public void run() {
                    //do some work with s.toString()
                }
            };
            handler.postDelayed(runnable, 500);
        }
    
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
    };
    

    Removing Handler on every onTextChanged (which is called when the user inputs a new character). afterTextChanged is called after the text has been changed inside input field where we can start new Runnable, but will cancel it if user types more characters (For more info, when these callback are called, see this). If user doesn't input anymore characters, interval will pass in postDelayed and it will call work you should do with that text.

    This code will run only once per interval, not for every key user inputs. Hope it helps someone in the future.

提交回复
热议问题