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

用 SpannableStringBuilder 為 TextView 局部文字上色

編輯:關於 Android 程式設計

想讓 TextView 中的部分文字呈現不同顏色?可以透過 SpannableStringBuilder 搭配 ForegroundColorSpan 來達成,讓同一段文字裡的不同片段各自套用不同的色彩。

程式碼實作

package cc.testspannablestringbuilder;

import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.widget.TextView;
import android.app.Activity;
import android.graphics.Color;

/**
 * Demo 描述: 利用 SpannableStringBuilder 設定 TextView 中部分文字的顏色
 *
 * 注意事項:
 * setSpan(new ForegroundColorSpan(Color.RED), 1, 3, Spannable.SPAN_EXCLUSIVE_INCLUSIVE)
 * 第一個參數: 顏色
 * 第二個參數: 開始位置
 * 第三個參數: 結束位置
 * 第四個參數: SPAN_EXCLUSIVE_INCLUSIVE,用來對第二、三個參數做進一步限制
 * 此處表示「不包含 1,但包含 3」
 */
public class MainActivity extends Activity {
    private TextView mTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        init();
    }

    private void init() {
        mTextView = (TextView) findViewById(R.id.textView);
        String str = " Hello everyone!";
        SpannableStringBuilder mSpannableStringBuilder = new SpannableStringBuilder(str);
        // 將索引 1~3 的文字設為紅色
        mSpannableStringBuilder.setSpan(
            new ForegroundColorSpan(Color.RED), 1, 3, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        // 將索引 5~9 的文字設為綠色
        mSpannableStringBuilder.setSpan(
            new ForegroundColorSpan(Color.GREEN), 5, 9, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        mTextView.setText(mSpannableStringBuilder);
    }
}

版面配置

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world"
        android:layout_centerInParent="true" />
</RelativeLayout>

關鍵在於 setSpan 的第四個參數 SPAN_EXCLUSIVE_INCLUSIVE,它決定了起訖位置的包含關係——此處代表「包含結束位置、但不包含起始位置」。只要調整這些索引值,就能為 TextView 中的任意片段套用不同顏色。

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