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

Android 走馬燈效果:TextView 與 Button 的 marquee 設定要點

編輯:關於 Android 程式設計

文字太長、空間太窄,又不想截斷——這時候走馬燈(marquee)是最直接的答案。ApiDemo 裡有 Button 的示範,但換成 TextView 時屬性組合略有不同,這裡把兩種都整理出來。

TextView 版本

<TextView
    android:layout_width="40px"
    android:layout_height="wrap_content"
    android:text="Test marquee for TextView"
    android:layout_gravity="center"
    android:ellipsize="marquee"
    android:singleLine="true"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:marqueeRepeatLimit="marquee_forever"
    android:scrollHorizontally="true" />

Button 版本

<Button
    android:id="@+id/buttonMarquee"
    android:layout_width="320px"
    android:layout_height="wrap_content"
    android:text="@string/textMarquee"
    android:singleLine="true"
    android:focusable="true"
    android:selectAllOnFocus="true"
    android:ellipsize="marquee"
    android:marqueeRepeatLimit="marquee_forever" />

其中 @string/textMarquee 定義在 res/values/strings.xml。

五個關鍵屬性

  • layout_width:必須比文字實際寬度短。顯示得完,自然就不必捲動了——這是最常被忽略的前提
  • ellipsize="marquee":宣告用走馬燈而非省略符號處理溢出
  • singleLine="true":限定單行,多行時 marquee 不會啟動
  • marqueeRepeatLimit="marquee_forever":無限次循環。也可指定次數,例如 marquee_forever 以外的整數
  • focusable / focusableInTouchMode:取得焦點是啟動動畫的觸發條件

為什麼設定了卻不動

十個有九個是因為「沒有取得焦點」。走馬燈只在該 View 處於 focused 或 selected 狀態時才會開始捲動。在觸控模式下,View 預設不可 focus,所以 focusableInTouchMode="true" 這一行是必要的;若用程式控制,可以呼叫 textView.requestFocus() 或 setSelected(true) 明確觸發。

另一個常見狀況是把 TextView 放進 ListView 的項目裡。此時焦點屬於整個項目列而非內部的 TextView,走馬燈不會啟動;解法是對 TextView 呼叫 setSelected(true),或改用 TextSwitcher、自訂 ValueAnimator 做位移動畫。

最後提醒,scrollHorizontally="true" 在 TextView 上建議一併加上,可避免文字被換行處理而讓 marquee 失效。至於 px 與 dp 的選用,範例沿用舊寫法用 px,實作時請改用 dp 以適配不同螢幕密度。

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