【Android 】TextView 區域性文字變色

許佳佳233發表於2016-11-07

TextView 對於富文字效果的實現支援不支援呢?比如“區域性文字顏色的變動”,“區域性字型的變動”

一、需求效果

這裡寫圖片描述

二、解決方案

針對這類問題,Android提供了 SpannableStringBuilder,方便我們自定義富文字的實現。

  textView = (TextView) findViewById(R.id.textview);
  SpannableStringBuilder builder = new SpannableStringBuilder(textView.getText().toString());

  //ForegroundColorSpan 為文字前景色,BackgroundColorSpan為文字背景色
  ForegroundColorSpan redSpan = new ForegroundColorSpan(Color.RED);
  ForegroundColorSpan whiteSpan = new ForegroundColorSpan(Color.WHITE);
  ForegroundColorSpan blueSpan = new ForegroundColorSpan(Color.BLUE);
  ForegroundColorSpan greenSpan = new ForegroundColorSpan(Color.GREEN);
  ForegroundColorSpan yellowSpan = new ForegroundColorSpan(Color.YELLOW);


  builder.setSpan(redSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  builder.setSpan(whiteSpan, 1, 2, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
  builder.setSpan(blueSpan, 2, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  builder.setSpan(greenSpan, 3, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  builder.setSpan(yellowSpan, 4,5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

  textView.setText(builder);

除了上述程式碼中使用的 ForegroundColorSpanBackgroundColorSpan之外,還有以下這些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—-如果設定了此風格,會有一條線從中間穿過所有的字,就像被劃掉一樣

三、動手試試

比如實現下圖中TextView的樣式

這裡寫圖片描述**

仿照上面的寫法,程式碼很少就出來啦:

TextView tv = (TextView)view.findViewById(R.id.toast_text);

String str1 = "提交成功!\n積分";
String str2 = "+" + score1;
String str3 = "!稽核通過後再";
String str4 = "+" + score2;

SpannableStringBuilder builder = new SpannableStringBuilder(str1 + str2 + str3 + str4 + "!");
builder.setSpan(new ForegroundColorSpan(Color.parseColor("#ffffa200")),
        str1.length(), (str1 + str2).length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
builder.setSpan(new ForegroundColorSpan(Color.parseColor("#ffffa200")),
        (str1 + str2 + str3).length(), (str1 + str2 + str3 + str4).length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);

tv.setText(builder);

##原文地址:
http://blog.csdn.net/u010983881/article/details/52383539?locationNum=2&fps=1

相關文章