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

Android TextView 常見效果速查:跑馬燈、多行省略與自動連結

編輯:關於 Android 程式設計

做 UI 時這幾個 TextView 屬性幾乎一定會用到,整理成速查筆記。

一、跑馬燈(Marquee)

android:singleLine="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:focusable="true"
android:focusableInTouchMode="true"

各屬性的作用:

  • android:singleLine="true":限定單行。多行顯示時跑馬燈沒有意義,因此這是必要條件。
  • android:ellipsize="marquee":文字過長時的處理方式,可選 none、start、middle、end;要跑馬燈就設 marquee。
  • android:marqueeRepeatLimit:滾動次數,marquee_forever 表示無止盡循環。
  • android:focusable 與 android:focusableInTouchMode:Android 的預設行為是「控制項取得焦點時才開始跑馬燈」。少了這兩行,在觸控模式下不會獲得焦點,文字就一直靜止不動——這是最常見的失敗原因。

二、超過指定行數後以省略號收尾

android:maxLines="2"
android:ellipsize="end"

maxLines 限制最多顯示兩行,ellipsize="end" 讓溢出部分在結尾以「…」表示。若想保留首尾而省略中段,可改用 middle;Android 2.x 之後亦可使用 android:ellipsize 搭配 breakStrategy(API 23+)做更細緻的控制。

三、自動辨識連結

android:autoLink="all"

可選值包含 phone(電話號碼)、email、map(地址)、web(網址)與 all,也能以 | 串接多種,例如 android:autoLink="phone|email|web"。啟用後對應文字會自動變成可點擊的連結。

四、補充:幾個高頻屬性

  • 行距:android:lineSpacingExtra 與 android:lineSpacingMultiplier,中文長段落可適度加大以改善可讀性。
  • 部分文字樣式:若需要「同一行裡不同顏色或字級」,用 SpannableString 搭配 ForegroundColorSpan 等,比拆成多個 TextView 更省資源。
  • 移除文字陰影:某些主題會自帶 textShadow,必要時以 android:shadowRadius="0" 關掉。
  • 避免硬編碼維度:文字大小請用 sp,以尊重使用者的系統字級設定。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved