取消光标重新定位并将当前光标位置保留在EditText中

时间:2015-08-25 17:57:13

标签: android android-edittext

我想禁用EditText中前几个字符的光标定位。

我已将EditText扩展为onSelectionChanged(),如下所示:

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

    text = this.getText();
    if (text != null) {
        if (start < NUM_FRONT_CHARACTERS || end < NUM_FRONT_CHARACTERS) {

            // Moves the cursor to the end
            setSelection(text.length(), text.length());

            return;
        }
    }

    super.onSelectionChanged(start, end);
}

如何取消光标重新定位,而不是将光标移动到EditText的末尾?

1 个答案:

答案 0 :(得分:0)

不要覆盖onSelectionChanged(),这太晚了,这是你不得不再次将选择设置到文本末尾的原因。改为覆盖setSelection(),只有在条件成立时才调用super.setSelection()。请注意,有两种方法可以设置必须覆盖的选择:

@Overrride
public void setSelection(int index) {
    if (index >= NUM_FRONT_CHARACTERS) {
        super.setSelection(index);
    }
}

@Overrride
public void setSelection(int start, int end) {
    if (start >= NUM_FRONT_CHARACTERS && end >= NUM_FRONT_CHARACTERS) {
        super.setSelection(start, end);
    }
}
相关问题