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 d开发者_如何学Cisturbing it's movement while the textview scrolls. Is it possible to insert text? Please help
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.
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 );
String old=textView.getText().toString();
String new= "pre"+old+"after"; // can manipulate using substring also
textView.setText(new);
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);
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());
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.
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);
}
精彩评论