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

TextView 限制字數並在超出的地方顯示省略號

編輯:關於 Android 開發

讓 TextView 過長時自動收尾成「...」

清單裡的暱稱、標題常常長度失控,把版面擠壞。要讓 TextView 只顯示固定字數、超出部分以太字號省略結尾,關鍵在於三個屬性同時搭配使用,少一個都不會如預期。

<TextView
    android:id="@+id/tvUserNameUgcListItem"
    android:layout_width="wrap_content"
    android:layout_height="@dimen/dp45"
    android:layout_marginLeft="@dimen/dp10"
    android:layout_toRightOf="@+id/ivUserImgUgcListItem"
    android:gravity="center_vertical"
    android:singleLine="true"
    android:maxEms="8"
    android:ellipsize="end"
    android:text="何問起 hovertree.com"
    android:textColor="@color/white_wall"
    android:textSize="@dimen/sp15" />

三個關鍵屬性

android:singleLine="true"
android:maxEms="8"
android:ellipsize="end"
  • singleLine:強制單行顯示。少了它,文字會換行,省略號自然無從談起。
  • maxEms:以「M」為單位限制寬度,設 8 就是最多容納 8 個 M 的寬度。這也是為什麼中文在裡頭看起來只放得下四個字——一個中文字約占兩個 M。
  • ellipsize="end":超出時在結尾顯示省略號。若想置中截斷可用 middle,想從開頭截斷則用 start。

實務上還有兩個替代思路值得知道:android:maxLength 是直接硬性截斷(不會出現省略號),而 maxLines="1" 加 ellipsize 則是新版 Android 偏好寫法,能避免使用 singleLine 帶來的效能與警告問題。

延伸參考:https://www.cnblogs.com/roucheng/p/androidwujie.html

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