TextWatcher events are being fired multiple times

后端 未结 7 2116
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-05 12:57

I have an annoying problem with TextWatcher. i\'ve been searching the web but couldnt find anything. appreciate if someone could assist me.

For some reason t

7条回答
  •  不知归路
    2020-12-05 13:24

    I tried all the solution answered on this question, none of those worked for me. But after some search I found this post. Using the RxJava to make the debounce worked well for me. Here goes my final solution:

    Add RxJava dependencies in the Gradle file:

    compile 'io.reactivex:rxandroid:1.0.1'
    compile 'io.reactivex:rxjava:1.0.14'
    compile 'com.artemzin.rxjava:proguard-rules:1.0.14.2'
    

    Implement your subject:

    PublishSubject yourSubject = PublishSubject.create();
        yourSubject .debounce(100, TimeUnit.MILLISECONDS)
                .onBackpressureLatest()
                .subscribe(s -> {
                    //Implements anything you want
                });
    

    Use your subject in your TextWatcher:

    TextWatcher myTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
    
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            yourSubject.onNext(s.toString()); //apply here your subject
        }
    
        @Override
        public void afterTextChanged(Editable s) {
        }
    };
    

    Add the TextWatcher in the EditText listener:

    my_edit_text.addTextChangedListener(myTextWatcher);
    

提交回复
热议问题