Need to center-align a single portion of text in a TextView

雨燕双飞 提交于 2019-12-07 10:20:24

问题


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!


回答1:


Maybe you could try to do this:

String t = "<center><font color=\"blue\">Test Blue.</font></center>";
text3.setText(Html.fromHtml(t)); 


来源:https://stackoverflow.com/questions/19818654/need-to-center-align-a-single-portion-of-text-in-a-textview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!