在EditText android中保留Cursor位置

时间:2015-08-20 02:30:20

标签: android-edittext android-cursor backspace

我有一个退格图像按钮,用于删除Editext字段中光标后的一个字符

<ImageButton
    android:id="@+id/backspace"/>

<EditText
    android:id="@+id/result"/>

这是代码

EditText resultEditText = (EditText)  getActivity().findViewById(R.id.result);

int curPostion;

curPostion = resultEditText.getSelectionEnd();

//getting the selected Text
SpannableStringBuilder selectedStr = new SpannableStringBuilder(resultEditText.getText());

//replacing the selected text with empty String
selectedStr.replace(curPostion - 1, curPostion, "");
resultEditText.setSelection(curPostion);

//Set new string
resultEditText.setText(selectedStr);

我的问题是,当我按退格键时,一个字符被成功删除,但光标会立即回到EditText的第一个位置。

删除字符后如何将光标保持在该位置?

我非常感谢你的帮助。非常感谢你。

1 个答案:

答案 0 :(得分:0)

我刚刚想出了解决方案,只需将一个新变量存储到新的光标位置然后再存储setSelection()。

详细

EditText resultEditText = (EditText)  getActivity().findViewById(R.id.result);

int curPostion;

curPostion = resultEditText.getSelectionEnd();

//getting the selected Text
SpannableStringBuilder selectedStr = new SpannableStringBuilder(resultEditText.getText());

//replacing the selected text with empty String
selectedStr.replace(curPostion - 1, curPostion, "");

//Store postition
int afterDelPosition = curPostion - 1;

//设置新字符串     resultEditText.setText(selectedStr);

//This will remain the cursor position
resultEditText.setSelection(afterDelPosition);

我希望这会有所帮助。