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

TextView 內容過寬時顯示省略號的設定方式

編輯:關於 Android 程式設計

清單裡的標題、作者名、檔名常常長度不可控,若不處理就會被硬性截斷或直接撐破版面。Android 的 TextView 內建了省略號支援,兩個屬性就能解決。

基本寫法

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/hello"
    android:ellipsize="end"
    android:singleLine="true" />

兩個屬性缺一不可:

  • android:singleLine="true":限制只顯示一行。少了這個,ellipsize 不會有效果,因為文字會換行而不是被截斷。
  • android:ellipsize="end":在結尾放省略號,也就是最常見的「某某某某…」效果。

ellipsize 的四種取值

  • none:不顯示省略號,預設值。
  • start:在開頭省略,變成「…某某某某」。適合路徑、URL 這類結尾才重要的內容。
  • middle:在中間省略,變成「某某…某某」。適合檔名,能同時保留副檔名與開頭。
  • end:在結尾省略,最常用於標題、人名。
  • marquee:跑馬燈效果,文字會水平捲動。它需要 TextView 取得焦點才會啟動,且对视覺與電池都不友善,正式產品不建議使用。

不用 singleLine 的寫法

singleLine 已被標記為不建議使用,比較現代的等價寫法是:

<TextView
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:ellipsize="end"
    android:maxLines="1" />

用 maxLines="1" 搭配 ellipsize 可以達到相同效果,而且行為更可控。layout_width="0dp" 加上 layout_weight 則是為了讓它在 LinearLayout 中正確分配剩餘寬度——若寫成 wrap_content,長文字會先主張自己的完整寬度,反而把兄弟 View 擠出去,省略號也就永遠不會出現。這是在 ListView 樣式中最常看到省略號失效的原因。

程式碼中動態設定

TextView tv = findViewById(R.id.hello);
tv.setSingleLine(true);
tv.setEllipsize(TextUtils.TruncateAt.END);

或者在 XML 中一次指定多行時,可用 android:maxLines="2" 搭配 ellipsize="end",讓文字最多兩行、超出部分在最後一行結尾省略,這在卡片式版面中很常用。

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