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

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

    You can also use TextWatcher interface and create your custom class that implements it to re-use many times your CustomTextWatcher and also you can pass views or whatever you might need to its constructor:

    public abstract class CustomTextWatcher implements TextWatcher { //Notice abstract class so we leave abstract method textWasChanged() for implementing class to define it
    
        private final TextView myTextView; //Remember EditText is a TextView so this works for EditText also
    
    
        public AddressTextWatcher(TextView tView) { //Notice I'm passing a view at the constructor, but you can pass other variables or whatever you need
            myTextView= tView;
    
        }
    
        private Timer timer = new Timer();
        private final int DELAY = 500; //milliseconds of delay for timer
    
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    
        }
    
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
    
        }
    
        @Override
        public void afterTextChanged(final Editable s) {
            timer.cancel();
            timer = new Timer();
    
            timer.schedule(
    
                    new TimerTask() {
                        @Override
                        public void run() {
                            textWasChanged();
                        }
                    },
                    DELAY
    
            );
        }
    
        public abstract void textWasChanged(); //Notice abstract method to leave implementation to implementing class
    
    }
    

    Now in your activity you can use it like this:

        myEditText.addTextChangedListener(new CustomTextWatcher(myEditText) { //Notice I'm passing in constructor of CustomTextWatcher myEditText I needed to use
            @Override
            public void textWasChanged() {
                //doSomething(); this is method inside your activity
            }
        });
    

提交回复
热议问题