4

I'm currently using SpannableString to format a large block of text in a single TextView. The size and color are formatted just fine, but I'm struggling with alignment.

I found this post that gave guidance on formatting for alignment, as well as this Android Developer page on how to use AlignmentSpan, but it doesn't seem to work for me. Eclipse shows no errors, the app loads/runs just fine, but the alignment piece seems to be completely ignored. Here's my code:

Spannable t = new SpannableString("Test Blue.");
t.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.color_blue)), 0, t.length()-1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
t.setSpan(new AbsoluteSizeSpan((int) getResources().getDimension(R.dimen.big_text)), 0, t.length()-1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
t.setSpan(new AlignmentSpan.Standard(Layout.Alignment.ALIGN_CENTER), 0, t.length()-1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
text3.setText(t);

Any help would be much appreciated.

[Edit] I've also tried commenting out both the color and size setSpans to see if there's a conflict, but no luck.

[Edit 2]: I marked the below answer as correct, but the correct answer is actually buried in the comments. I failed to update my XML file width for the TextView to match_parent (instead of fill_content). Thanks Serge!

Community
  • 1
  • 1
aikorei
  • 570
  • 1
  • 7
  • 23

1 Answers1

5

Maybe you could try to do this:

String t = "<center><font color=\"blue\">Test Blue.</font></center>";
text3.setText(Html.fromHtml(t)); 
serge
  • 1,590
  • 2
  • 26
  • 49
  • Thanks for the response, serge. This didn't work for me either. I was using HTML before trying Spannable strings, and couldn't find a satisfactory way to handle text size. To be clear, though, I did try your suggestion, but it didn't center the text either. Thanks anyhow. – aikorei Nov 06 '13 at 17:58
  • I see, ill keep looking – serge Nov 06 '13 at 17:59
  • 1
    Mybe you did not set your text width in XML to match parent so it doesn't have any room to center it inside the TextView – serge Nov 06 '13 at 18:05
  • Wow, good catch. I did change the XML to match_parent, but it still isn't centering. I figured that would fix it. – aikorei Nov 06 '13 at 18:17
  • My mistake! That actually did fix the problem, but I edited the wrong file. I edited the correct file, and now it works beautifully. Serge, I'm new around here...should I mark this answer as correct, or would you prefer to provide another answer (to change XML to match_parent) and I can check that one? – aikorei Nov 06 '13 at 18:39