views:

127

answers:

3

I want to insert a constant string into an EditText by the press of a button. The string should be inserted at the current position in the EditText. If I use EditText.append the text gets inserted at the end of the EditText.

How can I do that? I couldn't find a suitable method.

+1  A: 

Try using EditText.getSelectionStart() to get the current position of the cursor. Then you can use String.subString to get the text before and after the cursor and insert your text in the middle.

Haven't tried though.

Cpt.Ohlund
A: 

Cpt.Ohlund gave me the right hint. I solved it, now, partly with using EditText.getSelectionStart(), but I realized that you can also replace the selected text with the same expression and you don't need String.subString() for that.

int start = myEditText.getSelectionStart();
int end = myEditText.getSelectionEnd();
myEditText.getText().replace(Math.min(start, end), Math.max(start, end),
        textToInsert, 0, textToInsert.length());

This works for both, inserting a text at the current position and replacing whatever text is selected by the user. The Math.min() and Math.max() is necessary because the user could have selected the text backwards and thus start would have a higher value than end which is not allowed for Editable.replace().

Thanks to Cpt.Ohlund for putting me onto the right track and sorry for unnecessarily posting a question I anwered myself, in the end.

Manuel
A: 

Just so you know, the call you made to replace has a convenience defined for it (still called "replace" but less arguments to pass).

Documented here:

http://developer.android.com/reference/android/text/Editable.html#replace%28int,%20int,%20java.lang.CharSequence%29

Basically that saves you having to type "0, text.length()".

Scott