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

TextView 多行文字 ellipsize 無效?手動截斷加省略號的解法

編輯:關於 Android 程式設計

ellipsize 有個眾所皆知的限制:搭配 singleLine 或 lines="1" 時效果很好,但一旦文字超過多行,它就不會在最後一行加上省略號,反而容易出現文字被硬切、甚至顯示不全的情況。

解法是自己判斷行數,超過門檻就手動截斷並補上「...」。

一、版面檔中的 TextView

<TextView
    android:id="@+id/businesscardsingle_content_abstract"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="5dp"
    android:lineSpacingMultiplier="1.0"
    android:lines="6"
    android:text="@string/agrinbusiness_content"
    android:textColor="#7f7f7f"
    android:textSize="13sp" />

二、在 Java 中控制顯示行數

關鍵是透過 ViewTreeObserver 的 addOnGlobalLayoutListener,等到 View 完成版面計算、行數確定之後再處理:

ViewTreeObserver observer = textAbstract.getViewTreeObserver();  // textAbstract 為 TextView 控件
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

    @Override
    public void onGlobalLayout() {
        ViewTreeObserver obs = textAbstract.getViewTreeObserver();
        obs.removeGlobalOnLayoutListener(this);   // 只處理一次,避免無限觸發

        if (textAbstract.getLineCount() > 6) {    // 判斷行數是否超過門檻
            int lineEndIndex = textAbstract.getLayout().getLineEnd(5);  // 取第六行的結束位置
            String text = textAbstract.getText().subSequence(0, lineEndIndex - 3) + "...";
            textAbstract.setText(text);
        }
    }
});

程式邏輯拆解

  1. 為什麼要等版面完成:文字實際會換成幾行,取決於控件寬度、字級、行距等參數,這些在 onCreate 階段還沒計算出來,必須等 layout 完成後才能讀取。
  2. 務必移除監聽器:removeGlobalOnLayoutListener(this) 這行不能省,否則每次版面變化都會觸發一次,而 setText() 又會再觸發一次版面計算,形成迴圈。
  3. getLineEnd(5):取得索引 5(也就是第六行)的結束位置,前面保留 lineEndIndex - 3 個字元,剛好留出三個字元的空間給「...」。

一個更省事的做法

如果你的需求只是「固定行數 + 超出顯示省略號」,其實不必自己算位置。TextView 在較新的 API 上支援直接寫:

android:maxLines="6"
android:ellipsize="end"

這寫法在 API 16 以上能正確在第六行末尾顯示省略號,程式碼乾淨得多。上述手動截斷的方式主要價值在於舊版本相容,或是需要更精細控制(例如自訂截斷字數、保留特定結尾文字)的情境。

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