2015-08-20 72 views
0

我有一个退格图像按钮来删除Editext场次还光标现在的位置里面的EditText的Android

<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的第一个位置。

如何在删除字符后将光标停留在该位置?

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

回答

0

我刚想出解决方案,只是delcare一个新的变量来存储新的游标位置,然后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); 

我希望这会很有帮助。