Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android 跑馬燈效果:讓文字永遠滾動

網路上講跑馬燈的文章看多了會讓人失笑,因為幾乎每篇都會附一句「文字不能比 TextView 長」。想想就知道矛盾:文字都沒超過寬度,全都顯示出來了,還需要跑馬燈嗎?

真正的關鍵是:跑馬燈預設必須取得焦點才會啟動。想讓它任何時候都滾動,做法是繼承 TextView 並重寫 isFocused(),固定回傳 true。

public class MarqueeTextView extends TextView {

    public MarqueeTextView(Context context) {
        super(context);
    }

    public MarqueeTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MarqueeTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public boolean isFocused() {
        return true;
    }
}

接著在程式碼中設定三個屬性:

mText.setSingleLine(true);
mText.setEllipsize(TruncateAt.MARQUEE);
mText.setMarqueeRepeatLimit(-1);

三個設定各有分工:單行是前提,多行根本不會滾;ellipsize 指定為 MARQUEE 才會啟用滾動;repeat limit 設為 -1 表示無限次循環,不然跑幾趟就停了。若是在 XML 版面檔中,對應屬性為 android:singleLine、android:ellipsize="marquee" 與 android:marqueeRepeatLimit="marquee_forever"。這樣就完成了。

Copyright © Linux教程網 All Rights Reserved