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

Android 跑馬燈效果實作:幾個 XML 屬性就能搞定

編輯:關於 Android 程式設計

當 TextView 的文字長度超過可視寬度時,讓它從右向左循環捲動,就是所謂的跑馬燈效果。好消息是 Android 早已內建這個能力,不需要自訂 View,也不需要用上任何動畫框架,全部靠 XML 屬性即可完成。

實作後的樣子如下:

直接在版面配置中宣告

<TextView
    android:id="@+id/menu_desc"
    android:layout_width="300dip"
    android:layout_height="wrap_content"
    android:text="溫馨提示:左右滑動更改菜單,點擊進入"
    android:textColor="@color/white"
    android:textSize="22dip"
    android:singleLine="true"
    android:ellipsize="marquee"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:scrollHorizontally="true"
    android:marqueeRepeatLimit="marquee_forever"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true">
</TextView>

關鍵屬性逐項說明

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

其中 ellipsize="marquee" 是靈魂所在,決定文字溢出時以捲動方式呈現;marqueeRepeatLimit 控制循環次數,設為 marquee_forever 就是無限循環。而 focusable 與 focusableInTouchMode 這兩項最常被忽略——跑馬燈只有在控制項取得焦點時才會啟動,少了它們,即使其他屬性都寫對了畫面依然靜止不動。

另外建議搭配 android:scrollHorizontally="true" 與固定的 layout_width(如上例的 300dip)。若寬度設為 wrap_content,控制項會自動撐大到足以容納全文,反而沒有需要捲動的內容。

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