addTextChangedListener onTextChanged count Not working On android version 10

▼魔方 西西 提交于 2021-02-08 12:01:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!