README.md |
---|
Sometimes, we need to listen for changes in the TextView(also EditText) content, especially for some Android apps that support search, search suggestions is a very important feature that enhances the user experience. In general, Android developers prefer to use TextWatcher to listen to TextView content changes, such as follows
textView.addTextChangedListener(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) {
}
@Override public void afterTextChanged(Editable s) {
/*do suggestion search*/
doSearch(s.toString());
}
});
However, there is a problem here. If you want to search for "California," you may need at least four network requests such as "c", "a", "l", "i" to get the desired suggestions list. And these asynchronous network requests may eventually show the wrong suggestion list, without any special handling.
User experience! User experience! User experience! The important thing to speak three times!
We should do some debounce to avoid unnecessary network requests and avoid wasting bandwidth.
It's similar to javascript-debounce-function.
Download
Step 1. Add it in your root build.gradle at the end of repositories:
allprojects {
repositories {
maven { url 'https://jitpack.io' }
}
}
Step 2. Add the dependency
dependencies {
implementation 'com.github.SmartDengg:sug-debounce:1.1.0'
}
Useage
DebounceSubscription debounceSubscription = Debounce.onAfterTextChangedAction(textView, 300,
new DebounceObserver<TextViewAfterTextChangeEvent>() {
@Override public void onError(Throwable throwable) {
}
@Override public void onSuccess(TextViewAfterTextChangeEvent event) {
/*do your search*/
doSearch(event.editable().toString());
}
// release resource when not needed
debounceSubscription..unsubscribe();
You can change the denounce timeout
, but we recommend 300 ~ 400 ms.
Debounce
No-Debounce
TO-DO
❤️ Hope this article can help you. Support by clicking the ⭐, or share it with people around you. ❤️
Email : dengwei@lianjia.com
weibo : -小鄧子-
See the LICENSE file for license rights and limitations (MIT).