2

I am trying to create a function that will take a string "word" as an argument, apply span styling to the string and return it as a spannable string that I can ""+insert+"" into a string in a TextView. Thank you in advance for any help you can offer with this.

Here is the function I have so far.

public Spannable fr(String word){
  Spannable WordtoSpan = new SpannableString(word);        
  WordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 0, 
      word.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  WordtoSpan.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, 
      word.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  return WordtoSpan;
}

and the code that should display the spannable inline with my text.

TextView tview = (TextView) findViewById(R.id.accents_view);
tview.setText(Html.fromHtml("<strong>Text String</strong> "+fr("style_this"));

The application will either load the text without styling or the app will crash. Not sure what I'm doing wrong but I'm guessing it has something to do with mixing fromHtml text with spannables. Any work arounds?

If I remove the Html.fromHtml() and wrap the entire text with my fr() function it works. I get bold blue text. But I need to be able to make only certain words styled... It would also be nice to be able to reference vars from my string.xml file instead of hard coding them in, for multilingual support.

4

1 回答 1

0

我想你可能会觉得这很有帮助,

TextView tview = (TextView) findViewById(R.id.accents_view);
tview.setText(Html.fromHtml("<font color='blue'>Text</font> " 
    + "<font color='red'>String</font>"));
于 2013-12-25T03:27:08.017 回答