【郭林专刊】Android实战技巧:用TextView实现Rich Text---在同一个TextView中设置不同的字体风格...

背景介绍

在开发应用过程中经常会遇到显示一些不同的字体风格的信息犹如默认的LockScreen上面的时间和充电信息。对于类似的情况,可能第一反应就是用不同的多个TextView来实现,对于每个TextView设置不同的字体风格以满足需求。

这里推荐的做法是使用android.text.*;和android.text.style.*;下面的组件来实现RichText:也即在同一个TextView中设置不同的字体风格。对于某些应用,比如文本编辑,记事本,彩信,短信等地方,还必须使用这些组件才能达到想到的显示效果。

主要的基本工具类有android.text.Spanned; android.text.SpannableString; android.text.SpannableStringBuilder;使用这些类来代替常规String。SpannableString和SpannableStringBuilder可以用来设置不同的Span,这些Span便是用于实现Rich Text,比如粗体,斜体,前景色,背景色,字体大小,字体风格等等,android.text.style.*中定义了很多的Span类型可供使用。

这是相关的API的Class General Hierarchy:

因为Spannable等最终都实现了CharSequence接口,所以可以直接把SpannableString和SpannableStringBuilder通过TextView.setText()设置给TextView。

使用方法

当要显示Rich Text信息的时候,可以使用创建一个SpannableString或SpannableStringBuilder,它们的区别在于SpannableString像一个String一样,构造对象的时候传入一个String,之后再无法更改String的内容,也无法拼接多个SpannableString;而SpannableStringBuilder则更像是StringBuilder,它可以通过其append()方法来拼接多个String:

  1. SpannableStringword=newSpannableString("Thequickfoxjumpsoverthelazydog");
  2. SpannableStringBuildermultiWord=newSpannableStringBuilder();
  3. multiWord.append("TheQuickFox");
  4. multiWord.append("jumpsover");
  5. multiWord.append("thelazydog");
SpannableString word = new SpannableString("The quick fox jumps over the lazy dog"); SpannableStringBuilder multiWord = new SpannableStringBuilder(); multiWord.append("The Quick Fox"); multiWord.append("jumps over"); multiWord.append("the lazy dog"); 创建完Spannable对象后,就可以为它们设置Span来实现想要的Rich Text了,常见的Span有:
  • AbsoluteSizeSpan(int size) ---- 设置字体大小,参数是绝对数值,相当于Word中的字体大小
  • RelativeSizeSpan(float proportion) ---- 设置字体大小,参数是相对于默认字体大小的倍数,比如默认字体大小是x, 那么设置后的字体大小就是x*proportion,这个用起来比较灵活,proportion>1就是放大(zoom in), proportion<1就是缩小(zoom out)
  • ScaleXSpan(float proportion) ---- 缩放字体,与上面的类似,默认为1,设置后就是原来的乘以proportion,大于1时放大(zoon in),小于时缩小(zoom out)
  • BackgroundColorSpan(int color) ----背景着色,参数是颜色数值,可以直接使用android.graphics.Color里面定义的常量,或是用Color.rgb(int, int, int)
  • ForegroundColorSpan(int color) ----前景着色,也就是字的着色,参数与背景着色一致
  • TypefaceSpan(String family) ----字体,参数是字体的名字比如“sans", "sans-serif"等
  • StyleSpan(Typeface style) -----字体风格,比如粗体,斜体,参数是android.graphics.Typeface里面定义的常量,如Typeface.BOLD,Typeface.ITALIC等等。
  • StrikethroughSpan----如果设置了此风格,会有一条线从中间穿过所有的字,就像被划掉一样
对于这些Sytle span在使用的时候通常只传上面所说明的构造参数即可,不需要设置其他的属性,如果需要的话,也可以对它们设置其他的属性,详情可以参见文档
SpannableString和SpannableStringBuilder都有一个设置上述Span的方法:
  1. /**
  2. *SetthestylespantoSpannable,suchasSpannableStringorSpannableStringBuilder
  3. *@paramwhat---thestylespan,suchasStyleSpan
  4. *@paramstart---thestartingindexofcharacterstowhichthestylespantoapply
  5. *@paramend---theendingindexofcharacterstowhichthestylespantoapply
  6. *@paramflags---theflagspecifiedtocontrol
  7. */
  8. setSpan(Objectwhat,intstart,intend,intflags);
/** * Set the style span to Spannable, such as SpannableString or SpannableStringBuilder * @param what --- the style span, such as StyleSpan * @param start --- the starting index of characters to which the style span to apply * @param end --- the ending index of characters to which the style span to apply * @param flags --- the flag specified to control */ setSpan(Object what, int start, int end, int flags);

其中参数what是要设置的Style span,start和end则是标识String中Span的起始位置,而 flags是用于控制行为的,通常设置为0或Spanned中定义的常量,常用的有:

  • Spanned.SPAN_EXCLUSIVE_EXCLUSIVE --- 不包含两端start和end所在的端点
  • Spanned.SPAN_EXCLUSIVE_INCLUSIVE --- 不包含端start,但包含end所在的端点
  • Spanned.SPAN_INCLUSIVE_EXCLUSIVE --- 包含两端start,但不包含end所在的端点
  • Spanned.SPAN_INCLUSIVE_INCLUSIVE--- 包含两端start和end所在的端点
这里理解起来就好像数学中定义区间,开区间还是闭区间一样的。还有许多其他的Flag,可以参考这里。这里要重点说明下关于参数0,有很多时候,如果设置了上述的参数,那么Span会从start应用到Text结尾,而不是在start和end二者之间,这个时候就需要使用Flag 0。

权衡选择

个人认为软件开发中最常见的问题不是某个技巧怎么使用的问题,而是何时该使用何技巧的问题,因为实现同一个目标可能有N种不同的方法,就要权衡利弊,选择最合适的一个,正如常言所云,没有最好的,只有最适合的。如前面所讨论的,要想用不同的字体展现不同的信息可能的解法,除了用Style Span外还可以用多个TextView。那么就需要总结下什么时候该使用StyleSpan,什么时候该使用多个TextView:

  1. 如果显示的是多个不同类别的信息,就应该使用多个TextView,这样也方便控制和改变各自的信息,例子就是默认LockScreen上面的日期和充电信息,因为它们所承载不同的信息,所以应该使用多个TextView来分别呈现。
  2. 如果显示的是同一类信息,或者同一个信息,那么应该使用StyleSpan。比如,短信息中,要把联系人的相关信息突出显示;或是想要Highlight某些信息等。
  3. 如果要实现Rich text,没办法,只能使用Style span。
  4. 如果要实现某些特效,也可以考虑使用StyleSpan。设置不同的字体风格只是Style span的初级应用,如果深入研究,可以发现很多奇妙的功效。

实例

phone number, web address or email address,并标识为超链接,可点击,点击后便跳转到相应的应用,如Dialer,Browser或Email。

  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayout
  3. xmlns:android="http://schemas.android.com/apk/res/android"
  4. android:layout_width="wrap_content"
  5. android:layout_height="wrap_content"
  6. android:orientation="vertical">
  7. <ScrollView
  8. android:layout_width="fill_parent"
  9. android:layout_height="wrap_content">
  10. <LinearLayout
  11. android:layout_width="fill_parent"
  12. android:layout_height="wrap_content"
  13. android:orientation="vertical">
  14. <TextView
  15. android:id="@+id/text_view_font_1"
  16. android:layout_width="fill_parent"
  17. android:layout_height="wrap_content"
  18. />
  19. <TextView
  20. android:id="@+id/text_view_font_2"
  21. android:layout_width="fill_parent"
  22. android:layout_height="wrap_content"
  23. />
  24. <TextView
  25. android:id="@+id/text_view_font_3"
  26. android:layout_width="fill_parent"
  27. android:layout_height="wrap_content"
  28. />
  29. <TextView
  30. android:id="@+id/text_view_font_4"
  31. android:layout_width="fill_parent"
  32. android:layout_height="wrap_content"
  33. />
  34. <TextView
  35. android:id="@+id/text_view_font_5"
  36. android:layout_width="fill_parent"
  37. android:layout_height="wrap_content"
  38. />
  39. </LinearLayout>
  40. </ScrollView>
  41. </LinearLayout>
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical"> <ScrollView android:layout_width="fill_parent" android:layout_height="wrap_content"> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:id="@+id/text_view_font_1" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <TextView android:id="@+id/text_view_font_2" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <TextView android:id="@+id/text_view_font_3" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <TextView android:id="@+id/text_view_font_4" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <TextView android:id="@+id/text_view_font_5" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout> </ScrollView> </LinearLayout> Source code:
  1. packagecom.android.effective;
  2. importjava.util.regex.Matcher;
  3. importjava.util.regex.Pattern;
  4. importandroid.app.Activity;
  5. importandroid.graphics.Color;
  6. importandroid.graphics.Typeface;
  7. importandroid.os.Bundle;
  8. importandroid.text.Spannable;
  9. importandroid.text.SpannableString;
  10. importandroid.text.SpannableStringBuilder;
  11. importandroid.text.style.AbsoluteSizeSpan;
  12. importandroid.text.style.BackgroundColorSpan;
  13. importandroid.text.style.ForegroundColorSpan;
  14. importandroid.text.style.QuoteSpan;
  15. importandroid.text.style.RelativeSizeSpan;
  16. importandroid.text.style.ScaleXSpan;
  17. importandroid.text.style.StrikethroughSpan;
  18. importandroid.text.style.StyleSpan;
  19. importandroid.text.style.TypefaceSpan;
  20. importandroid.text.style.URLSpan;
  21. importandroid.text.util.Linkify;
  22. importandroid.widget.TextView;
  23. publicclassTextViewFontActivityextendsActivity{
  24. @Override
  25. publicvoidonCreate(Bundlebundle){
  26. super.onCreate(bundle);
  27. setContentView(R.layout.textview_font_1);
  28. //DemonstrationofbasicSpannableStringandspansusage
  29. finalTextViewtextWithString=(TextView)findViewById(R.id.text_view_font_1);
  30. Stringw="Thequickfoxjumpsoverthelazydog";
  31. intstart=w.indexOf('q');
  32. intend=w.indexOf('k')+1;
  33. Spannableword=newSpannableString(w);
  34. word.setSpan(newAbsoluteSizeSpan(22),start,end,
  35. Spannable.SPAN_INCLUSIVE_INCLUSIVE);
  36. word.setSpan(newStyleSpan(Typeface.BOLD),start,end,
  37. Spannable.SPAN_INCLUSIVE_INCLUSIVE);
  38. word.setSpan(newBackgroundColorSpan(Color.RED),start,end,
  39. Spannable.SPAN_INCLUSIVE_INCLUSIVE);
  40. textWithString.setText(word);
  41. //DemonstrationofbasicSpannableStringBuilderandspansusage
  42. finalTextViewtextWithBuilder=(TextView)findViewById(R.id.text_view_font_2);
  43. SpannableStringBuilderword2=newSpannableStringBuilder();
  44. finalStringone="Freedomisnothingbutachancetobebetter!";
  45. finalStringtwo="Thequickfoxjumpsoverthelazydog!";
  46. finalStringthree="Thetreeoflibertymustberefreshedfromtimetotimewith"+
  47. "thebloodofpatroitsandtyrants!";
  48. word2.append(one);
  49. start=0;
  50. end=one.length();
  51. word2.setSpan(newStyleSpan(Typeface.BOLD_ITALIC),start,end,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  52. word2.append(two);
  53. start=end;
  54. end+=two.length();
  55. word2.setSpan(newForegroundColorSpan(Color.CYAN),start,end,
  56. Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  57. word2.append(three);
  58. start=end;
  59. end+=three.length();
  60. word2.setSpan(newURLSpan(three),start,end,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  61. textWithBuilder.setText(word2);
  62. //TroubleshootingwhenusingSpannableStringBuilder
  63. finalTextViewtextTroubles=(TextView)findViewById(R.id.text_view_font_3);
  64. SpannableStringBuilderword3=newSpannableStringBuilder();
  65. start=0;
  66. end=one.length();
  67. //Caution:mustfirstappendorsettexttoSpannableStringBuilderorSpannableString
  68. //thensetthespanstothem,otherwise,IndexOutOfBoundExceptionisthrownwhensettingspans
  69. word3.append(one);
  70. //ForAbsoluteSizeSpan,theflagmustbesetto0,otherwise,itwillapplythisspantountilendoftext
  71. word3.setSpan(newAbsoluteSizeSpan(22),start,end,0);//Spannable.SPAN_INCLUSIVE_INCLUSIVE);
  72. //ForBackgroundColorSpanSpan,theflagmustbesetto0,otherwise,itwillapplythisspantoendoftext
  73. word3.setSpan(newBackgroundColorSpan(Color.DKGRAY),start,end,0);//Spannable.SPAN_INCLUSIVE_INCLUSIVE);
  74. word3.append(two);
  75. start=end;
  76. end+=two.length();
  77. word3.setSpan(newTypefaceSpan("sans-serif"),start,end,
  78. Spannable.SPAN_INCLUSIVE_INCLUSIVE);
  79. //TODO:sometimes,flagmustbesetto0,otherwiseitwillapplythespantountilendoftext
  80. //whichMIGHThasnothingtodowithspecificspantype.
  81. word3.setSpan(newStyleSpan(Typeface.BOLD_ITALIC),start,end,0);//Spannable.SPAN_INCLUSIVE_INCLUSIVE);
  82. word3.setSpan(newScaleXSpan(0.618f),start,end,Spannable.SPAN_INCLUSIVE_INCLUSIVE);
  83. word3.setSpan(newStrikethroughSpan(),start,end,0);//Spannable.SPAN_INCLUSIVE_INCLUSIVE);
  84. word3.setSpan(newForegroundColorSpan(Color.CYAN),start,end,Spannable.SPAN_INCLUSIVE_INCLUSIVE);
  85. word3.setSpan(newQuoteSpan(),start,end,0);//Spannable.SPAN_INCLUSIVE_INCLUSIVE);
  86. word3.append(three);
  87. start=end;
  88. end+=three.length();
  89. word3.setSpan(newRelativeSizeSpan((float)Math.E),start,end,Spannable.SPAN_INCLUSIVE_INCLUSIVE);
  90. word3.setSpan(newForegroundColorSpan(Color.BLUE),start,end,Spannable.SPAN_INCLUSIVE_INCLUSIVE);
  91. textTroubles.setText(word3);
  92. //Highlightsomepatterns
  93. finalStringfour="Thegapbetweenthebestsoftwareengineering"+
  94. "practiceandtheaveragepracticeisverywide¡ªperhapswider"+
  95. "thaninanyotherengineeringdiscipline.Atoolthatdisseminates"+
  96. "goodpracticewouldbeimportant.¡ªFredBrooks";
  97. finalPatternhighlight=Pattern.compile("the");
  98. finalTextViewtextHighlight=(TextView)findViewById(R.id.text_view_font_4);
  99. SpannableStringword4=newSpannableString(four);
  100. Matcherm=highlight.matcher(word4.toString());
  101. while(m.find()){
  102. word4.setSpan(newStyleSpan(Typeface.BOLD_ITALIC),m.start(),m.end(),
  103. Spannable.SPAN_INCLUSIVE_INCLUSIVE);
  104. word4.setSpan(newForegroundColorSpan(Color.RED),m.start(),m.end(),
  105. Spannable.SPAN_INCLUSIVE_INCLUSIVE);
  106. word4.setSpan(newStrikethroughSpan(),m.start(),m.end(),
  107. Spannable.SPAN_INCLUSIVE_INCLUSIVE);
  108. }
  109. textHighlight.setText(word4);
  110. //Setnumbers,URLsandE-mailaddresstobeclickablewithTextView#setAutoLinkMask
  111. finalTextViewtextClickable=(TextView)findViewById(R.id.text_view_font_5);
  112. finalStringcontact="Email:mvp@microsoft.com\n"+
  113. "Phone:+47-24885883\n"+
  114. "Fax:+47-24885883\n"+
  115. "HTTP:www.microsoft.com/mvp.asp";
  116. //Settheattributefirst,thensetthetext.Otherwise,itwon'twork
  117. textClickable.setAutoLinkMask(Linkify.ALL);//orset'android:autoLink'inlayoutxml
  118. textClickable.setText(contact);
  119. }
  120. }
package com.android.effective; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.app.Activity; import android.graphics.Color; import android.graphics.Typeface; import android.os.Bundle; import android.text.Spannable; import android.text.SpannableString; import android.text.SpannableStringBuilder; import android.text.style.AbsoluteSizeSpan; import android.text.style.BackgroundColorSpan; import android.text.style.ForegroundColorSpan; import android.text.style.QuoteSpan; import android.text.style.RelativeSizeSpan; import android.text.style.ScaleXSpan; import android.text.style.StrikethroughSpan; import android.text.style.StyleSpan; import android.text.style.TypefaceSpan; import android.text.style.URLSpan; import android.text.util.Linkify; import android.widget.TextView; public class TextViewFontActivity extends Activity { @Override public void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView(R.layout.textview_font_1); // Demonstration of basic SpannableString and spans usage final TextView textWithString = (TextView) findViewById(R.id.text_view_font_1); String w = "The quick fox jumps over the lazy dog"; int start = w.indexOf('q'); int end = w.indexOf('k') + 1; Spannable word = new SpannableString(w); word.setSpan(new AbsoluteSizeSpan(22), start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE); word.setSpan(new StyleSpan(Typeface.BOLD), start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE); word.setSpan(new BackgroundColorSpan(Color.RED), start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE); textWithString.setText(word); // Demonstration of basic SpannableStringBuilder and spans usage final TextView textWithBuilder = (TextView) findViewById(R.id.text_view_font_2); SpannableStringBuilder word2 = new SpannableStringBuilder(); final String one = "Freedom is nothing but a chance to be better!"; final String two = "The quick fox jumps over the lazy dog!"; final String three = "The tree of liberty must be refreshed from time to time with " + "the blood of patroits and tyrants!"; word2.append(one); start = 0; end = one.length(); word2.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); word2.append(two); start = end; end += two.length(); word2.setSpan(new ForegroundColorSpan(Color.CYAN), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); word2.append(three); start = end; end += three.length(); word2.setSpan(new URLSpan(three), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); textWithBuilder.setText(word2); // Troubleshooting when using SpannableStringBuilder final TextView textTroubles = (TextView) findViewById(R.id.text_view_font_3); SpannableStringBuilder word3 = new SpannableStringBuilder(); start = 0; end = one.length(); // Caution: must first append or set text to SpannableStringBuilder or SpannableString // then set the spans to them, otherwise, IndexOutOfBoundException is thrown when setting spans word3.append(one); // For AbsoluteSizeSpan, the flag must be set to 0, otherwise, it will apply this span to until end of text word3.setSpan(new AbsoluteSizeSpan(22), start, end, 0);//Spannable.SPAN_INCLUSIVE_INCLUSIVE); // For BackgroundColorSpanSpan, the flag must be set to 0, otherwise, it will apply this span to end of text word3.setSpan(new BackgroundColorSpan(Color.DKGRAY), start, end, 0); //Spannable.SPAN_INCLUSIVE_INCLUSIVE); word3.append(two); start = end; end += two.length(); word3.setSpan(new TypefaceSpan("sans-serif"), start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE); // TODO: sometimes, flag must be set to 0, otherwise it will apply the span to until end of text // which MIGHT has nothing to do with specific span type. word3.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), start, end, 0);//Spannable.SPAN_INCLUSIVE_INCLUSIVE); word3.setSpan(new ScaleXSpan(0.618f), start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE); word3.setSpan(new StrikethroughSpan(), start, end, 0);//Spannable.SPAN_INCLUSIVE_INCLUSIVE); word3.setSpan(new ForegroundColorSpan(Color.CYAN), start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE); word3.setSpan(new QuoteSpan(), start, end, 0); //Spannable.SPAN_INCLUSIVE_INCLUSIVE); word3.append(three); start = end; end += three.length(); word3.setSpan(new RelativeSizeSpan((float) Math.E), start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE); word3.setSpan(new ForegroundColorSpan(Color.BLUE), start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE); textTroubles.setText(word3); // Highlight some patterns final String four = "The gap between the best software engineering " + "practice and the average practice is very wide¡ªperhaps wider " + " than in any other engineering discipline. A tool that disseminates " + "good practice would be important.¡ªFred Brooks"; final Pattern highlight = Pattern.compile("the"); final TextView textHighlight = (TextView) findViewById(R.id.text_view_font_4); SpannableString word4 = new SpannableString(four); Matcher m = highlight.matcher(word4.toString()); while (m.find()) { word4.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), m.start(), m.end(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); word4.setSpan(new ForegroundColorSpan(Color.RED), m.start(), m.end(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); word4.setSpan(new StrikethroughSpan(), m.start(), m.end(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); } textHighlight.setText(word4); // Set numbers, URLs and E-mail address to be clickable with TextView#setAutoLinkMask final TextView textClickable = (TextView) findViewById(R.id.text_view_font_5); final String contact = "Email: mvp@microsoft.com\n" + "Phone: +47-24885883\n" + "Fax: +47-24885883\n" + "HTTP: www.microsoft.com/mvp.asp"; // Set the attribute first, then set the text. Otherwise, it won't work textClickable.setAutoLinkMask(Linkify.ALL); // or set 'android:autoLink' in layout xml textClickable.setText(contact); } } The results:


背景介绍

在开发应用过程中经常会遇到显示一些不同的字体风格的信息犹如默认的LockScreen上面的时间和充电信息。对于类似的情况,可能第一反应就是用不同的多个TextView来实现,对于每个TextView设置不同的字体风格以满足需求。

这里推荐的做法是使用android.text.*;和android.text.style.*;下面的组件来实现RichText:也即在同一个TextView中设置不同的字体风格。对于某些应用,比如文本编辑,记事本,彩信,短信等地方,还必须使用这些组件才能达到想到的显示效果。

主要的基本工具类有android.text.Spanned; android.text.SpannableString; android.text.SpannableStringBuilder;使用这些类来代替常规String。SpannableString和SpannableStringBuilder可以用来设置不同的Span,这些Span便是用于实现Rich Text,比如粗体,斜体,前景色,背景色,字体大小,字体风格等等,android.text.style.*中定义了很多的Span类型可供使用。

这是相关的API的Class General Hierarchy:

因为Spannable等最终都实现了CharSequence接口,所以可以直接把SpannableString和SpannableStringBuilder通过TextView.setText()设置给TextView。

使用方法

当要显示Rich Text信息的时候,可以使用创建一个SpannableString或SpannableStringBuilder,它们的区别在于SpannableString像一个String一样,构造对象的时候传入一个String,之后再无法更改String的内容,也无法拼接多个SpannableString;而SpannableStringBuilder则更像是StringBuilder,它可以通过其append()方法来拼接多个String:

  1. SpannableStringword=newSpannableString("Thequickfoxjumpsoverthelazydog");
  2. SpannableStringBuildermultiWord=newSpannableStringBuilder();
  3. multiWord.append("TheQuickFox");
  4. multiWord.append("jumpsover");
  5. multiWord.append("thelazydog");
SpannableString word = new SpannableString("The quick fox jumps over the lazy dog"); SpannableStringBuilder multiWord = new SpannableStringBuilder(); multiWord.append("The Quick Fox"); multiWord.append("jumps over"); multiWord.append("the lazy dog"); 创建完Spannable对象后,就可以为它们设置Span来实现想要的Rich Text了,常见的Span有:
  • AbsoluteSizeSpan(int size) ---- 设置字体大小,参数是绝对数值,相当于Word中的字体大小
  • RelativeSizeSpan(float proportion) ---- 设置字体大小,参数是相对于默认字体大小的倍数,比如默认字体大小是x, 那么设置后的字体大小就是x*proportion,这个用起来比较灵活,proportion>1就是放大(zoom in), proportion<1就是缩小(zoom out)
  • ScaleXSpan(float proportion) ---- 缩放字体,与上面的类似,默认为1,设置后就是原来的乘以proportion,大于1时放大(zoon in),小于时缩小(zoom out)
  • BackgroundColorSpan(int color) ----背景着色,参数是颜色数值,可以直接使用android.graphics.Color里面定义的常量,或是用Color.rgb(int, int, int)
  • ForegroundColorSpan(int color) ----前景着色,也就是字的着色,参数与背景着色一致
  • TypefaceSpan(String family) ----字体,参数是字体的名字比如“sans", "sans-serif"等
  • StyleSpan(Typeface style) -----字体风格,比如粗体,斜体,参数是android.graphics.Typeface里面定义的常量,如Typeface.BOLD,Typeface.ITALIC等等。
  • StrikethroughSpan----如果设置了此风格,会有一条线从中间穿过所有的字,就像被划掉一样
对于这些Sytle span在使用的时候通常只传上面所说明的构造参数即可,不需要设置其他的属性,如果需要的话,也可以对它们设置其他的属性,详情可以参见文档
SpannableString和SpannableStringBuilder都有一个设置上述Span的方法:
  1. /**
  2. *SetthestylespantoSpannable,suchasSpannableStringorSpannableStringBuilder
  3. *@paramwhat---thestylespan,suchasStyleSpan
  4. *@paramstart---thestartingindexofcharacterstowhichthestylespantoapply
  5. *@paramend---theendingindexofcharacterstowhichthestylespantoapply
  6. *@paramflags---theflagspecifiedtocontrol
  7. */
  8. setSpan(Objectwhat,intstart,intend,intflags);
/** * Set the style span to Spannable, such as SpannableString or SpannableStringBuilder * @param what --- the style span, such as StyleSpan * @param start --- the starting index of characters to which the style span to apply * @param end --- the ending index of characters to which the style span to apply * @param flags --- the flag specified to control */ setSpan(Object what, int start, int end, int flags);

其中参数what是要设置的Style span,start和end则是标识String中Span的起始位置,而 flags是用于控制行为的,通常设置为0或Spanned中定义的常量,常用的有:

  • Spanned.SPAN_EXCLUSIVE_EXCLUSIVE --- 不包含两端start和end所在的端点
  • Spanned.SPAN_EXCLUSIVE_INCLUSIVE --- 不包含端start,但包含end所在的端点
  • Spanned.SPAN_INCLUSIVE_EXCLUSIVE --- 包含两端start,但不包含end所在的端点
  • Spanned.SPAN_INCLUSIVE_INCLUSIVE--- 包含两端start和end所在的端点
这里理解起来就好像数学中定义区间,开区间还是闭区间一样的。还有许多其他的Flag,可以参考这里。这里要重点说明下关于参数0,有很多时候,如果设置了上述的参数,那么Span会从start应用到Text结尾,而不是在start和end二者之间,这个时候就需要使用Flag 0。

权衡选择

个人认为软件开发中最常见的问题不是某个技巧怎么使用的问题,而是何时该使用何技巧的问题,因为实现同一个目标可能有N种不同的方法,就要权衡利弊,选择最合适的一个,正如常言所云,没有最好的,只有最适合的。如前面所讨论的,要想用不同的字体展现不同的信息可能的解法,除了用Style Span外还可以用多个TextView。那么就需要总结下什么时候该使用StyleSpan,什么时候该使用多个TextView:

  1. 如果显示的是多个不同类别的信息,就应该使用多个TextView,这样也方便控制和改变各自的信息,例子就是默认LockScreen上面的日期和充电信息,因为它们所承载不同的信息,所以应该使用多个TextView来分别呈现。
  2. 如果显示的是同一类信息,或者同一个信息,那么应该使用StyleSpan。比如,短信息中,要把联系人的相关信息突出显示;或是想要Highlight某些信息等。
  3. 如果要实现Rich text,没办法,只能使用Style span。
  4. 如果要实现某些特效,也可以考虑使用StyleSpan。设置不同的字体风格只是Style span的初级应用,如果深入研究,可以发现很多奇妙的功效。

实例

phone number, web address or email address,并标识为超链接,可点击,点击后便跳转到相应的应用,如Dialer,Browser或Email。

  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayout
  3. xmlns:android="http://schemas.android.com/apk/res/android"
  4. android:layout_width="wrap_content"
  5. android:layout_height="wrap_content"
  6. android:orientation="vertical">
  7. <ScrollView
  8. android:layout_width="fill_parent"
  9. android:layout_height="wrap_content">
  10. <LinearLayout
  11. android:layout_width="fill_parent"
  12. android:layout_height="wrap_content"
  13. android:orientation="vertical">
  14. <TextView
  15. android:id="@+id/text_view_font_1"
  16. android:layout_width="fill_parent"
  17. android:layout_height="wrap_content"
  18. />
  19. <TextView
  20. android:id="@+id/text_view_font_2"
  21. android:layout_width="fill_parent"
  22. android:layout_height="wrap_content"
  23. />
  24. <TextView
  25. android:id="@+id/text_view_font_3"
  26. android:layout_width="fill_parent"
  27. android:layout_height="wrap_content"
  28. />
  29. <TextView
  30. android:id="@+id/text_view_font_4"
  31. android:layout_width="fill_parent"
  32. android:layout_height="wrap_content"
  33. />
  34. <TextView
  35. android:id="@+id/text_view_font_5"
  36. android:layout_width="fill_parent"
  37. android:layout_height="wrap_content"
  38. />
  39. </LinearLayout>
  40. </ScrollView>
  41. </LinearLayout>
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical"> <ScrollView android:layout_width="fill_parent" android:layout_height="wrap_content"> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:id="@+id/text_view_font_1" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <TextView android:id="@+id/text_view_font_2" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <TextView android:id="@+id/text_view_font_3" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <TextView android:id="@+id/text_view_font_4" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <TextView android:id="@+id/text_view_font_5" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout> </ScrollView> </LinearLayout> Source code:
  1. packagecom.android.effective;
  2. importjava.util.regex.Matcher;
  3. importjava.util.regex.Pattern;
  4. importandroid.app.Activity;
  5. importandroid.graphics.Color;
  6. importandroid.graphics.Typeface;
  7. importandroid.os.Bundle;
  8. importandroid.text.Spannable;
  9. importandroid.text.SpannableString;
  10. importandroid.text.SpannableStringBuilder;
  11. importandroid.text.style.AbsoluteSizeSpan;
  12. importandroid.text.style.BackgroundColorSpan;
  13. importandroid.text.style.ForegroundColorSpan;
  14. importandroid.text.style.QuoteSpan;
  15. importandroid.text.style.RelativeSizeSpan;
  16. importandroid.text.style.ScaleXSpan;
  17. importandroid.text.style.StrikethroughSpan;
  18. importandroid.text.style.StyleSpan;
  19. importandroid.text.style.TypefaceSpan;
  20. importandroid.text.style.URLSpan;
  21. importandroid.text.util.Linkify;
  22. importandroid.widget.TextView;
  23. publicclassTextViewFontActivityextendsActivity{
  24. @Override
  25. publicvoidonCreate(Bundlebundle){
  26. super.onCreate(bundle);
  27. setContentView(R.layout.textview_font_1);
  28. //DemonstrationofbasicSpannableStringandspansusage
  29. finalTextViewtextWithString=(TextView)findViewById(R.id.text_view_font_1);
  30. Stringw="Thequickfoxjumpsoverthelazydog";
  31. intstart=w.indexOf('q');
  32. intend=w.indexOf('k')+1;
  33. Spannableword=newSpannableString(w);
  34. word.setSpan(newAbsoluteSizeSpan(22),start,end,
  35. Spannable.SPAN_INCLUSIVE_INCLUSIVE);
  36. word.setSpan(newStyleSpan(Typeface.BOLD),start,end,
  37. Spannable.SPAN_INCLUSIVE_INCLUSIVE);
  38. word.setSpan(newBackgroundColorSpan(Color.RED),start,end,
  39. Spannable.SPAN_INCLUSIVE_INCLUSIVE);
  40. textWithString.setText(word);
  41. //DemonstrationofbasicSpannableStringBuilderandspansusage
  42. finalTextViewtextWithBuilder=(TextView)findViewById(R.id.text_view_font_2);
  43. SpannableStringBuilderword2=newSpannableStringBuilder();
  44. finalStringone="Freedomisnothingbutachancetobebetter!";
  45. finalStringtwo="Thequickfoxjumpsoverthelazydog!";
  46. finalStringthree="Thetreeoflibertymustberefreshedfromtimetotimewith"+
  47. "thebloodofpatroitsandtyrants!";
  48. word2.append(one);
  49. start=0;
  50. end=one.length();
  51. word2.setSpan(newStyleSpan(Typeface.BOLD_ITALIC),start,end,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  52. word2.append(two);
  53. start=end;
  54. end+=two.length();
  55. word2.setSpan(newForegroundColorSpan(Color.CYAN),start,end,
  56. Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  57. word2.append(three);
  58. start=end;
  59. end+=three.length();
  60. word2.setSpan(newURLSpan(three),start,end,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  61. textWithBuilder.setText(word2);
  62. //TroubleshootingwhenusingSpannableStringBuilder
  63. finalTextViewtextTroubles=(TextView)findViewById(R.id.text_view_font_3);
  64. SpannableStringBuilderword3=newSpannableStringBuilder();
  65. start=0;
  66. end=one.length();
  67. //Caution:mustfirstappendorsettexttoSpannableStringBuilderorSpannableString
  68. //thensetthespanstothem,otherwise,IndexOutOfBoundExceptionisthrownwhensettingspans
  69. word3.append(one);
  70. //ForAbsoluteSizeSpan,theflagmustbesetto0,otherwise,itwillapplythisspantountilendoftext
  71. word3.setSpan(newAbsoluteSizeSpan(22),start,end,0);//Spannable.SPAN_INCLUSIVE_INCLUSIVE);
  72. //ForBackgroundColorSpanSpan,theflagmustbesetto0,otherwise,itwillapplythisspantoendoftext
  73. word3.setSpan(newBackgroundColorSpan(Color.DKGRAY),start,end,0);//Spannable.SPAN_INCLUSIVE_INCLUSIVE);
  74. word3.append(two);
  75. start=end;
  76. end+=two.length();
  77. word3.setSpan(newTypefaceSpan("sans-serif"),start,end,
  78. Spannable.SPAN_INCLUSIVE_INCLUSIVE);
  79. //TODO:sometimes,flagmustbesetto0,otherwiseitwillapplythespantountilendoftext
  80. //whichMIGHThasnothingtodowithspecificspantype.
  81. word3.setSpan(newStyleSpan(Typeface.BOLD_ITALIC),start,end,0);//Spannable.SPAN_INCLUSIVE_INCLUSIVE);
  82. word3.setSpan(newScaleXSpan(0.618f),start,end,Spannable.SPAN_INCLUSIVE_INCLUSIVE);
  83. word3.setSpan(newStrikethroughSpan(),start,end,0);//Spannable.SPAN_INCLUSIVE_INCLUSIVE);
  84. word3.setSpan(newForegroundColorSpan(Color.CYAN),start,end,Spannable.SPAN_INCLUSIVE_INCLUSIVE);
  85. word3.setSpan(newQuoteSpan(),start,end,0);//Spannable.SPAN_INCLUSIVE_INCLUSIVE);
  86. word3.append(three);
  87. start=end;
  88. end+=three.length();
  89. word3.setSpan(newRelativeSizeSpan((float)Math.E),start,end,Spannable.SPAN_INCLUSIVE_INCLUSIVE);
  90. word3.setSpan(newForegroundColorSpan(Color.BLUE),start,end,Spannable.SPAN_INCLUSIVE_INCLUSIVE);
  91. textTroubles.setText(word3);
  92. //Highlightsomepatterns
  93. finalStringfour="Thegapbetweenthebestsoftwareengineering"+
  94. "practiceandtheaveragepracticeisverywide¡ªperhapswider"+
  95. "thaninanyotherengineeringdiscipline.Atoolthatdisseminates"+
  96. "goodpracticewouldbeimportant.¡ªFredBrooks";
  97. finalPatternhighlight=Pattern.compile("the");
  98. finalTextViewtextHighlight=(TextView)findViewById(R.id.text_view_font_4);
  99. SpannableStringword4=newSpannableString(four);
  100. Matcherm=highlight.matcher(word4.toString());
  101. while(m.find()){
  102. word4.setSpan(newStyleSpan(Typeface.BOLD_ITALIC),m.start(),m.end(),
  103. Spannable.SPAN_INCLUSIVE_INCLUSIVE);
  104. word4.setSpan(newForegroundColorSpan(Color.RED),m.start(),m.end(),
  105. Spannable.SPAN_INCLUSIVE_INCLUSIVE);
  106. word4.setSpan(newStrikethroughSpan(),m.start(),m.end(),
  107. Spannable.SPAN_INCLUSIVE_INCLUSIVE);
  108. }
  109. textHighlight.setText(word4);
  110. //Setnumbers,URLsandE-mailaddresstobeclickablewithTextView#setAutoLinkMask
  111. finalTextViewtextClickable=(TextView)findViewById(R.id.text_view_font_5);
  112. finalStringcontact="Email:mvp@microsoft.com\n"+
  113. "Phone:+47-24885883\n"+
  114. "Fax:+47-24885883\n"+
  115. "HTTP:www.microsoft.com/mvp.asp";
  116. //Settheattributefirst,thensetthetext.Otherwise,itwon'twork
  117. textClickable.setAutoLinkMask(Linkify.ALL);//orset'android:autoLink'inlayoutxml
  118. textClickable.setText(contact);
  119. }
  120. }
package com.android.effective; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.app.Activity; import android.graphics.Color; import android.graphics.Typeface; import android.os.Bundle; import android.text.Spannable; import android.text.SpannableString; import android.text.SpannableStringBuilder; import android.text.style.AbsoluteSizeSpan; import android.text.style.BackgroundColorSpan; import android.text.style.ForegroundColorSpan; import android.text.style.QuoteSpan; import android.text.style.RelativeSizeSpan; import android.text.style.ScaleXSpan; import android.text.style.StrikethroughSpan; import android.text.style.StyleSpan; import android.text.style.TypefaceSpan; import android.text.style.URLSpan; import android.text.util.Linkify; import android.widget.TextView; public class TextViewFontActivity extends Activity { @Override public void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView(R.layout.textview_font_1); // Demonstration of basic SpannableString and spans usage final TextView textWithString = (TextView) findViewById(R.id.text_view_font_1); String w = "The quick fox jumps over the lazy dog"; int start = w.indexOf('q'); int end = w.indexOf('k') + 1; Spannable word = new SpannableString(w); word.setSpan(new AbsoluteSizeSpan(22), start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE); word.setSpan(new StyleSpan(Typeface.BOLD), start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE); word.setSpan(new BackgroundColorSpan(Color.RED), start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE); textWithString.setText(word); // Demonstration of basic SpannableStringBuilder and spans usage final TextView textWithBuilder = (TextView) findViewById(R.id.text_view_font_2); SpannableStringBuilder word2 = new SpannableStringBuilder(); final String one = "Freedom is nothing but a chance to be better!"; final String two = "The quick fox jumps over the lazy dog!"; final String three = "The tree of liberty must be refreshed from time to time with " + "the blood of patroits and tyrants!"; word2.append(one); start = 0; end = one.length(); word2.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); word2.append(two); start = end; end += two.length(); word2.setSpan(new ForegroundColorSpan(Color.CYAN), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); word2.append(three); start = end; end += three.length(); word2.setSpan(new URLSpan(three), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); textWithBuilder.setText(word2); // Troubleshooting when using SpannableStringBuilder final TextView textTroubles = (TextView) findViewById(R.id.text_view_font_3); SpannableStringBuilder word3 = new SpannableStringBuilder(); start = 0; end = one.length(); // Caution: must first append or set text to SpannableStringBuilder or SpannableString // then set the spans to them, otherwise, IndexOutOfBoundException is thrown when setting spans word3.append(one); // For AbsoluteSizeSpan, the flag must be set to 0, otherwise, it will apply this span to until end of text word3.setSpan(new AbsoluteSizeSpan(22), start, end, 0);//Spannable.SPAN_INCLUSIVE_INCLUSIVE); // For BackgroundColorSpanSpan, the flag must be set to 0, otherwise, it will apply this span to end of text word3.setSpan(new BackgroundColorSpan(Color.DKGRAY), start, end, 0); //Spannable.SPAN_INCLUSIVE_INCLUSIVE); word3.append(two); start = end; end += two.length(); word3.setSpan(new TypefaceSpan("sans-serif"), start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE); // TODO: sometimes, flag must be set to 0, otherwise it will apply the span to until end of text // which MIGHT has nothing to do with specific span type. word3.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), start, end, 0);//Spannable.SPAN_INCLUSIVE_INCLUSIVE); word3.setSpan(new ScaleXSpan(0.618f), start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE); word3.setSpan(new StrikethroughSpan(), start, end, 0);//Spannable.SPAN_INCLUSIVE_INCLUSIVE); word3.setSpan(new ForegroundColorSpan(Color.CYAN), start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE); word3.setSpan(new QuoteSpan(), start, end, 0); //Spannable.SPAN_INCLUSIVE_INCLUSIVE); word3.append(three); start = end; end += three.length(); word3.setSpan(new RelativeSizeSpan((float) Math.E), start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE); word3.setSpan(new ForegroundColorSpan(Color.BLUE), start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE); textTroubles.setText(word3); // Highlight some patterns final String four = "The gap between the best software engineering " + "practice and the average practice is very wide¡ªperhaps wider " + " than in any other engineering discipline. A tool that disseminates " + "good practice would be important.¡ªFred Brooks"; final Pattern highlight = Pattern.compile("the"); final TextView textHighlight = (TextView) findViewById(R.id.text_view_font_4); SpannableString word4 = new SpannableString(four); Matcher m = highlight.matcher(word4.toString()); while (m.find()) { word4.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), m.start(), m.end(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); word4.setSpan(new ForegroundColorSpan(Color.RED), m.start(), m.end(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); word4.setSpan(new StrikethroughSpan(), m.start(), m.end(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); } textHighlight.setText(word4); // Set numbers, URLs and E-mail address to be clickable with TextView#setAutoLinkMask final TextView textClickable = (TextView) findViewById(R.id.text_view_font_5); final String contact = "Email: mvp@microsoft.com\n" + "Phone: +47-24885883\n" + "Fax: +47-24885883\n" + "HTTP: www.microsoft.com/mvp.asp"; // Set the attribute first, then set the text. Otherwise, it won't work textClickable.setAutoLinkMask(Linkify.ALL); // or set 'android:autoLink' in layout xml textClickable.setText(contact); } } The results:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值