Android TextView Marquee 跑馬燈文字

TextView Marquee

針對 TextView 中過長的文字,可以讓它像跑馬燈一樣左右移動。

設定 TextView

當你想要 TextView 以一行的方式來顯示文字,可是有的文字太長無法全部顯示,這時可以指定 TextView 的相關屬性讓過長的文字以跑馬燈的方式顯示。
<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 
  xmlns:android="http://schemas.android.com/apk/res/android" 
  android:orientation="vertical" 
  android:layout_width="match_parent" 
  android:layout_height="match_parent"> 
    <TextView 
      android:textAppearance="?android:attr/textAppearanceLarge" 
      android:layout_height="wrap_content" 
      android:layout_width="wrap_content" 
      android:id="@+id/txtMarquee" 
      android:text="這是文字過長跑馬燈測試,看到請回答,OVER~~" 
      android:textSize="30sp" 
      android:marqueeRepeatLimit="-1" 
      android:ellipsize="marquee" 
      android:singleLine="true" 
      android:padding="5sp" 
      android:focusableInTouchMode="true" 
      android:focusable="true" /> 
</LinearLayout>

TextView 屬性說明

android:marqueeRepeatLimit="-1"

跑馬燈的循環次數,-1表示無限循環。

android:singleLine="true"

指定TextView以單行顯示。

android:focusableInTouchMode="true"

指定在觸控模式下取得焦點,連同下一個focusable都必須設為true,跑馬燈才會動。

android:focusable="true"

讓TextView可以取得焦點。

android:ellipsize="marquee"

過長文字的省略方式,共有5種:
  • none:不作用。形同end。
  • start:省略開頭文字,注重顯示尾端文字。
  • middle:省略中間文字,前後文字中間以...呈現。
  • end:省略尾端文字。
  • marquee:跑馬燈模式。
在程式碼裡不需再做其他設定。
本文網址:http://blog.tonycube.com/2011/08/textview-marquee.html
Tony Blog 撰寫,請勿全文複製,轉載時請註明出處及連結,謝謝 😀

2 則留言

  1. 請問如果要做上下滾動的跑馬燈,要如何做呢?!
    有辦法一樣只做屬性的變動就好嗎?

    回覆刪除
    回覆
    1. 這功能是內建的,如果要上下手捲動,可以參考這篇
      http://stackoverflow.com/questions/25731123/android-animations-similar-to-make-marquee-vertical

      刪除

留言小提醒:
1.回覆時間通常在晚上,如果太忙可能要等幾天。
2.請先瀏覽一下其他人的留言,也許有人問過同樣的問題。
3.程式碼請先將它編碼後再貼上。(線上編碼:http://bit.ly/1DL6yog)
4.文字請加上標點符號及斷行,難以閱讀者恕難回覆。
5.感謝您的留言,您的問題也可能幫助到其他有相同問題的人。