EditText光标定位问题

问题描述 投票:0回答:2

我正在使用下面的函数强制在Edittext中将每个单词的第一个字母设置为大写字母。

 public String capitalizeFirstLetterWord(String s) {
    StringBuilder cap = new StringBuilder();
    for (int i = 0; i < s.length(); i++) {
        try {
            char x = s.charAt(i);
            if (x == ' ') {
                cap.append(" ");
                char y = s.charAt(i + 1);
                cap.append(Character.toUpperCase(y));
                i++;
            } else {
                cap.append(x);
            }
        } catch (IndexOutOfBoundsException ignored) {

        }
    }
    //finally, capitalize the first letter of the sentence
    String sentence = cap.toString();
    if (sentence.length() > 0) {
        sentence = String.valueOf(sentence.charAt(0)).toUpperCase(); //capitalize first letter

        if (cap.toString().length() > 1) { //check if there's succeeding letters
            sentence += cap.toString().substring(1); //append it also
        }
    }
    return sentence;
}

并在afterTextChange()方法中调用它,如下所示:

  @Override
    public void afterTextChanged(Editable editable) {
        if (getActivity().getCurrentFocus() == mEdtName) {
            if (editable.toString().length() > 0 &&
                    !editable.toString().equals(mOldName)) {
                mOldName = editable.toString(); //prevent infinite loop
             mEdtName.setText(capitalizeFirstLetterWord(editable.toString()));
mEdName.setSelection(mEdGymName.getText().length()); //set the cursor to the end of the editText
            }
        }
    }

但是,问题是当我试图从Editext中的整个字符串的中间删除一个字符。光标在文本末尾移动。 。这是因为afterTextChanged()方法中的以下行。如果我对该行进行注释,则Cursor移动到第一个位置。 。

可能是什么解决方案?

android android-edittext
2个回答
0
投票

试试这个 :

@Override
public void afterTextChanged(Editable editable) {
    if (getActivity().getCurrentFocus() == mEdtName) {
        if (editable.toString().length() > 0 && !editable.toString().equals(mOldName)) {

            int selection = mEditName.getSelectionEnd();

            mOldName = editable.toString(); //prevent infinite loop
            mEditName.removeTextChangedListener(this);
       mEditName.setText(capitalizeFirstLetterWord(editable.toString()));
            mEditName.setSelection(selection);
            mEditName.addTextChangedListener(this);
        }
    }
}

0
投票

我认为你应该使用InputFilter来做到这一点。

© www.soinside.com 2019 - 2024. All rights reserved.