Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 初階開發

Android TextView 局部字元高亮:用 LinearLayout 拆解每一個字

編輯:初階開發

TextView 並不支援局部文字高亮,但我們可以繞道而行。

思路

1. 用 LinearLayout 作為整段文字的容器。
2. 字串中的每一個字,各自用一個 TextView 顯示。
3. 還可以用 *.9.png(Nine-patch)作為所有 TextView 的共同背景,讓它們看起來像一個整體。

拆成單字之後,要改變某幾個字的顏色就變成一件輕鬆的事——直接找到對應的 TextView 改屬性即可。

實作步驟

1. 定義 TextHighlightHelper 的建構子

傳入 Activity 上下文與子檢視的排列方向(水平或垂直),以及 layout 的寬高:

public class TextHighlightHelper {

    Activity activity;
    LinearLayout lLayout;

    public TextHighlightHelper(Activity a, int orientation) {
        activity = a;
        lLayout = new LinearLayout(activity);
        lLayout.setOrientation(orientation);
        lLayout.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
    }
}

2. 接收字串的 addText 方法

// 每個字元都各自用一個 TextView 顯示
// 這樣做的好處是後續設定顏色非常容易
public void addText(CharSequence cs) {
    for (int i = 0; i < cs.length(); i++) {
        TextView tv = new TextView(activity);
        tv.setText(cs.charAt(i) + "");
        lLayout.addView(tv);
    }
}

3. 設定部分字元顏色的 addColor 方法

// 從 s 開始,連續 l 個字元,顏色都設為 c
public void addColor(int s, int l, int c) {
    if (l > lLayout.getChildCount()) {
        // 參數錯誤
    } else {
        for (int i = s; i < s + l; i++) {
            TextView item = (TextView) lLayout.getChildAt(i);
            item.setTextColor(c);
        }
    }
}

4. 設定所有字元的背景

這裡最好使用 *.9.png 資源,因為文字長度可變,Nine-patch 能自動拉伸而不變形:

public void addBackResource(int r) {
    lLayout.setBackgroundResource(r);
}

5. 取得整個 LinearLayout 供外部使用

public View loadView() {
    return lLayout;
}

6. 怎麼用

先在版面檔中定義最外層容器的 id:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:id="@+id/layout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView
        android:text="HelloText1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

然後在 Activity 中使用:

public class TextHighlightUsage extends Activity {

    TextHighlightHelper tHelper1;
    TextHighlightHelper tHelper2;
    LinearLayout ll;

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

        ll = (LinearLayout) findViewById(R.id.layout);

        // 文字:HelloText2
        CharSequence c1 = "HelloText2";
        tHelper1 = new TextHighlightHelper(this, LinearLayout.HORIZONTAL);
        tHelper1.addText(c1);
        tHelper1.addColor(0, 3, Color.RED);
        tHelper1.addBackResource(R.drawable.dot);
        ll.addView(tHelper1.loadView());

        // 文字:創新源於模仿!
        CharSequence c2 = "創新源於模仿!";
        tHelper2 = new TextHighlightHelper(this, LinearLayout.VERTICAL);
        tHelper2.addText(c2);
        tHelper2.addColor(1, 3, Color.RED);
        ll.addView(tHelper2.loadView());
    }
}

第一組是水平排列的 HelloText2,前三個字(Hel)標成紅色;第二組是垂直排列的中文,從第 1 個字起連續 3 個字標紅。垂直排列時每個字各佔一列,正好可以做出直書的效果。

至於這個方案能不能滿足你的需求,就見仁見智了,可以參考上面的截圖自行判斷。

先別急著這樣做:更簡單的替代方案

在動手拆字之前,請先確認你真的需要這麼做。上面這個方法的問題不少:

效能差。一段 100 字的文字會產生 100 個 TextView 物件,每個都是完整的檢視,量測與繪製成本遠高於一個 TextView。清單中若有幾十列這種內容,捲動會明顯卡頓。

無法選取與複製。文字被拆散後,長按選字、複製、分享這些系統行為全部失效。

無障礙性受損。螢幕閱讀器會把每個字當成獨立元件朗讀,體驗極差。

版面對齊困難。字距、行距、標點符號的位置都需要額外微調,中英文混排時尤其明顯。

在大多數情況下,Android 其實已經內建局部樣式的支援,用 SpannableString 就能做到,而且只產生一個 TextView:

String text = "創新源於模仿!";
SpannableString ss = new SpannableString(text);

ss.setSpan(new ForegroundColorSpan(Color.RED), 1, 4,
        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
ss.setSpan(new StyleSpan(Typeface.BOLD), 0, 3,
        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
ss.setSpan(new BackgroundColorSpan(Color.YELLOW), 5, 6,
        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
ss.setSpan(new RelativeSizeSpan(1.5f), 0, 2,
        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

textView.setText(ss);

常用的 Span 還包括 StrikethroughSpan(刪除線)、UnderlineSpan(底線)、SuperscriptSpan(上標)、ClickableSpan(可點擊片段)等。若是想讓畫面中的某幾個字有不同顏色,ForegroundColorSpan 一行就解決了。

在 Kotlin 中更簡潔,AndroidX Core 提供了 buildSpannedString:

val styled = buildSpannedString {
    append("創新")
    color(Color.RED) { append("源於") }
    bold { append("模仿") }
    append("!")
}

結論:拆字成多個 TextView 是歷史上因工具不足而生的做法。今天的 Android 有 Spannable、有 AnnotatedString(Compose),都能用一個元件完成同樣的事,同時保留複製、選取與無障礙支援。上面那套 Helper 值得一看之處,在於它示範了「把介面拆解成最小單位再組合」的思路,但真正實作時請優先考慮 Spannable。

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