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

Android 為 TextView/Button 實作跑馬燈效果

編輯:關於 Android 程式設計

在 Android 的 ApiDemo 中可以看到 Button 的跑馬燈效果,但同樣的效果套用到 TextView 時,卻存在一些差異需要注意。

跑馬燈(Marquee)效果主要在 res/layout/main.xml 中定義,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:marqueeRepeatLimit="marquee_forever"
    android:focusableInTouchMode="true"
    android:scrollHorizontally="true"
 />

幾個關鍵點:

(1)layout_width 設定的長度必須比文字實際長度短,也就是文字顯示不開時才會出現跑馬燈效果。

(2)ellipsize 宣告使用 marquee 跑馬燈。

(3)singleLine 表示單行顯示。

(4)marqueeRepeatLimit 表示跑馬燈顯示的次數,marquee_forever 代表無限制、不間斷顯示。

此外,TextView 之所以需要 focusable 與 focusableInTouchMode,是因為跑馬燈效果必須在元件取得焦點時才會啟動。

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"
/>

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