indira
indira

Reputation: 6687

Is it possible to insert text in an TextView?

Appending text in an Android TextView adds the text to the end of the current text. I want to insert some text in a specified location of a TextView without disturbing it's movement while the textview scrolls. Is it possible to insert text? Please help

Upvotes: 2

Views: 16175

Answers (7)

sasha_trn
sasha_trn

Reputation: 2015

You can set BufferType of TextView as Editable. It is required only once.

textView.setText(textView.getText(), BufferType.EDITABLE);

Then you can use:

((Editable) textView.getText()).insert(where, text)

I believe this way is more efficient if you need to insert text often.

Upvotes: 6

Gena Batsyan
Gena Batsyan

Reputation: 736

A little off-topic, but if your 'TextView' happens to be EditText...

EditText.getText() actually returns an Editable, not CharSequence or String as one might expect. Editable does have methods to insert and replace text.

    Editable e = editText.getText();
    e.insert(pos, text);
    e.replace(start, end, text);
    // etc.

The above methods crafting a new string from substrings and then putting it to back to editText is OK, however if your text had any markup it would be lost. Contrary to that editable.insert() / replace() preserves any markup outside of inserted/replaced text.

Upvotes: 1

Michell Bak
Michell Bak

Reputation: 13252

Try this:

private void insertTextAtPoint(String textToAdd, int point) {
  private textBefore = textView.substring(0, point);
  private textAfter = textView.substring(point, textView.getText().toString().length);
  textView.setText(textBefore + textToAdd + textAfter);
}

Upvotes: 0

Android Killer
Android Killer

Reputation: 18499

You can do like this and this probably easiest way to do this

    String text_view_text=textView.getText().toString();
    StringBuffer sb=new StringBuffer(text_view_text);
    sb.insert(position_to_insert,text_to_insert);
    textView.setText(sb.toString());

Upvotes: 1

ilango j
ilango j

Reputation: 6037

try like below using string buffer.

String string=yourTextView.getText().toString();

StringBuffer sb=new StringBuffer(string);

    sb.insert(index, "string_to_insert");

string=sb.toString();

yourTextView.setText(string);

Upvotes: 1

kaspermoerch
kaspermoerch

Reputation: 16570

I would read the text currently in the TextView, split it at the point I wanted to insert and then put it all together. Like this:

String text = myTextView.getText().toString();
String first = text.substring( 0, splitPoint );
String second = text.substring( splitPoint, text.length );

myTextView.setText( first + insertText + second );

Upvotes: 2

jazz
jazz

Reputation: 1216

String old=textView.getText().toString();

String new= "pre"+old+"after"; // can manipulate using substring also

textView.setText(new);

Upvotes: 1

Related Questions