EditText - Cursor coming to start for every letter when clear text

巧了我就是萌 提交于 2019-12-24 10:49:43

问题


I set TextWatcher to EditText like below. But when I try to clear text, cursor is coming to start after clearing every letter.

  class MyInputWatcher implements 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) {
        et.removeTextChangedListener(watcher2);
        et.setText(s.toString().replaceAll("[^[:alpha:]]", ""));
        et.addTextChangedListener(watcher2);
    }
    @Override
    public void afterTextChanged(Editable s) {

    }
}

回答1:


Please try like this

editText.setSelection(editText.getText().toString().length());



回答2:


Subhash Kumar, you can use method:

et.setSelection(position)

for displaying cursor in need position




回答3:


Set position to your cursor on afterTextChanged() method like this.

class MyInputWatcher implements 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) {
    et.removeTextChangedListener(watcher2);
    et.setText(s.toString().replaceAll("[^[:alpha:]]", ""));
    et.addTextChangedListener(watcher2);
}
@Override
public void afterTextChanged(Editable s) {
    et.setSelection(et.getText().toString().length())
}

}




回答4:


Every time you clear a character it calls onTextChanged() method, as your implementation it get the edittext text and back set to it, so the cursor comes to the starting of the text. Clear et.setText(s.toString().replaceAll("[^[:alpha:]]", "")); and it will be fixed. Or use this et.setSelection(et.getText().toString().length+1);




回答5:


Do it like this (UPDATED):

class MyInputWatcher implements 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) {
        String temp = s.toString().replaceAll("[^a-zA-Z]", "");
        if (s.toString().length() != temp.length()) {
            et.setText(temp);
            et.setSelection(temp.length());
        }
    }

    @Override
    public void afterTextChanged(Editable s) {
    }
}


来源:https://stackoverflow.com/questions/41953259/edittext-cursor-coming-to-start-for-every-letter-when-clear-text

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