Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android TextView 進階技巧:為部分文字設置背景色與前景色

編輯:關於 Android 程式設計

想讓 TextView 裡的某幾個字顯示出不同的顏色或背景?借助 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);
    }
}

把這套邏輯封裝成一個方法,項目中調用起來就更方便了:

// textview 設置部分顏色
public SpannableStringBuilder setPartColorText(String str) {
    // 使用 SpannableStringBuilder 類
    SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(str);
    // 確定部分顏色的位置
    int start = str.indexOf(content);
    int end = start + content.length();
    // 確定顏色為紅色
    ForegroundColorSpan mForeColor = new ForegroundColorSpan(Color.RED);
    // setSpan
    spannableStringBuilder.setSpan(mForeColor, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    return spannableStringBuilder;
}

除了前景與背景着色,SpannableString 家族還提供了豐富的 Span 類型,可以實現更多樣的文本效果:

AbsoluteSizeSpan(int size) —— 設置字體大小,參數為絕對數值,相當於 Word 中直接指定字號。

RelativeSizeSpan(float proportion) —— 設置字體大小,參數為相對於默認字體大小的倍數。若默認字體為 x,設置後即為 x * proportion,使用起來更靈活:proportion > 1 放大,proportion < 1 縮小。

ScaleXSpan(float proportion) —— 橫向縮放字體,默認為 1,設置後為原值乘以 proportion,大於 1 放大,小於 1 縮小。

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 —— 設置後會有一條線從文字中間穿過,呈現刪除線效果。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved