4

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

Fahadsk
  • 1,099
  • 10
  • 24
Rahul R
  • 303
  • 2
  • 11
  • I think if you change the text, you're going to have to call `setSpan()` again for both fonts. To make this look a little better in code, you could create a class that extends `TextView` that has 2 setters for the text that is different and performs the `setSpan()` calls under the covers. Another possible option is to format your text with HTML and use `Html.fromHtml()` to prepare it for use in a standard TextView. Here is an example of that: https://stackoverflow.com/questions/2116162/how-to-display-html-in-textview. – Bradford2000 May 25 '17 at 15:23

2 Answers2

1

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");
Alyoshak
  • 2,696
  • 10
  • 43
  • 70
0

Can you try something like this :

public void updateTextView(String toThis) {
    TextView textView = (TextView) findViewById(R.id.textView);
    textView.setText(toThis);
// Put here your span, ...
}

And call this function when you want update your textView

CBJul
  • 31
  • 4