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"?
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With