Insert Android EditText

How to insert characters in the middle of an EditText field?
I am making a calculator that can take a string expression like "3 * (10 ^ 2-8)". I use the EditText field to make a string using XML as follows:

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 work I will say:

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

Now I have an EditText field when the cursor blinks after the third character in the line. How to insert a character there, so he correctly says "blahblahblah"?

+6
source share
2 answers

The getText () method 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 specific position.

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

 Editable text = entry.getText(); text.insert(entry.getSelectionStart(), "h"); 
+4
source

Say you have String str and it contains "blablahblah" and you want to do this "blahblahblah", you can do the following:

 String newString = str.substring(0, 3) + "h" + str.substring(3); 

Take the first 3, add a new letter, put everything else. That way, you can take a line from EditText, change it like that, and then put the new String in the new EditText value.

0
source

Source: https://habr.com/ru/post/905475/


All Articles