Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android EditText inserting

How do I insert characters into the middle of an EditText field?
I'm making a calculator that can take a string expression like "3*(10^2-8)". I'm using an EditText field to make the string using XML like so:

EditText

android:id="@+id/entry"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/label"
android:text="@string/testString1"
android:background="@android:drawable/editbox_background"

and then in my activity I have, say:

entry = (EditText)findViewById(R.id.entry);
entry.setText("blablahblah");
entry.setSelection(3);

Now I have an EditText field with the cursor blinking after the third character in the string. How do I insert a character there, so it correctly says "blahblahblah"?

like image 304
Bill Maney Avatar asked Jan 08 '12 22:01

Bill Maney


1 Answers

The method getText() of the EditText widget returns an object that implements the Editable interface. On this object you can call the insert() method to insert text at a certain position.

I found this out by reading the documentation, but never used this myself. But for your needs, to insert a character at the selected position in the EditText, the following should work:

Editable text = entry.getText();
text.insert(entry.getSelectionStart(), "h");
like image 128
Jan-Henk Avatar answered Oct 09 '22 10:10

Jan-Henk