在editText

时间:2017-04-24 16:50:21

标签: android android-edittext

我正在尝试将光标放在editText字段的末尾,这样用户就无法开始在中间输入信息。我尝试使用onClickListener和onTouchListener将选择设置为editText的长度。即使尝试了这两种方法,用户仍然可以将光标移动到文本的中间位置。有办法防止这种情况吗?

1 个答案:

答案 0 :(得分:0)

You can use myEditText.setSelection(text.length()) to set the cursor at the end of the EditText in conjuction with the onSelectionChanged() method.

Taken from: https://stackoverflow.com/a/12982251/1269953

@Override
public void onSelectionChanged(int start, int end) {

    CharSequence text = getText();
    if (text != null) {
        if (start != text.length() || end != text.length()) {
            setSelection(text.length(), text.length());
            return;
        }
    }

    super.onSelectionChanged(start, end);
}

This will revert the cursor back to the end of the text.