Can i change span Text in android

Viewed 1098

Here is my code,i want to put two type of fonts in my Textview. I can successfully implement a code to do that.My problem is i want to edit the variable text without changing the arrangement.

String text = " my font1 , font 2 ";   
Typeface font,font1;
font = Typeface.createFromAsset(getAssets(), "font.TTF");
font1 = Typeface.createFromAsset(getAssets(), "font1.TTF");
Spannable s = new SpannableString(text);
s.setSpan(new CustomTypefaceSpan("", font), curpos, endpos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
s.setSpan(new CustomTypefaceSpan("", font1), curpos, endpos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
.
.
.
.
//want to chage variable text here !

I reffered the following but i don't get the solution.

Set color of TextView span in Android

Android: Coloring part of a string using TextView.setText()?

TextView with different textSize

2 Answers

Try using the SpannableStringBuilder class. "This is the class for text whose content and markup can both be changed." It sounds like you need a mutable class.

It's unclear precisely how you want to change the text, but I use SpannableStringBuilder like this to insert additional text at the beginning of some text that is html. Once you have your string builder object there are sufficient methods available to modify things.

 Spanned spHtml = Html.fromHtml(myHtmlString, Html.FROM_HTML_MODE_LEGACY);
 SpannableStringBuilder sb = new SpannableStringBuilder(spHtml);
 sb.insert(0, "text to be inserted");
Related