问题
I use addTextChangedListener to search item from server with retrofit. but only android version 10 onTextChanged count not working...?
Here is my code
searchEdit.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) {
if (count>1) {
String name = searchEdit.getText().toString().trim();
if (!name.isEmpty()) {
searchItemByName(name);
}
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
回答1:
I'll go with the assumption that you're using count parameter in onTextChanged callback as the number of characters inside your searchEdit Edittext.
Solution:
You need to use s.length() function instead of the parameter count, like this:
searchEdit.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) {
if (s.length()>1) {
String name = searchEdit.getText().toString().trim();
if (!name.isEmpty()) {
searchItemByName(name);
}
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
Explanation:
If you have a look at the documentation of android.text.TextWatcher::onTextChanged function below:
/**
* This method is called to notify you that, within <code>s</code>,
* the <code>count</code> characters beginning at <code>start</code>
* have just replaced old text that had length <code>before</code>.
* It is an error to attempt to make changes to <code>s</code> from
* this callback.
*/
public void onTextChanged(CharSequence s, int start, int before, int count);
it says that count parameter refers to the number of characters changed in s, and thus, if you're typing into the edittext your onTextChanged function will be called with the parameter count is 1.
Alternatively: you can use afterTextChanged callback with s.length().
来源:https://stackoverflow.com/questions/65613326/addtextchangedlistener-ontextchanged-count-not-working-on-android-version-10