通過SpannableStringBuilder來實現,它就像html里邊的元素改變指定文字的文字顏色或背景色
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); String str="這是設置TextView部分文字背景顏色和前景顏色的demo!"; int bstart=str.indexOf("背景"); int bend=bstart+"背景".length(); int fstart=str.indexOf("前景"); int fend=fstart+"前景".length(); SpannableStringBuilder style=new SpannableStringBuilder(str); style.setSpan(new BackgroundColorSpan(Color.RED),bstart,bend,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); style.setSpan(new ForegroundColorSpan(Color.RED),fstart,fend,Spannable.SPAN_EXCLUSIVE_INCLUSIVE); TextView tvColor=(TextView) findViewById(R.id.tv_color); tvColor.setText(style); } }

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----如果設置了此風格,會有一條線從中間穿過所有的字,就像被划掉一樣
原文:http://www.2cto.com/kf/201409/335648.html
