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

Android TextView 文字跑馬燈滾動效果實現

編輯:關於 Android 程式設計

Android TextView 字體滾動效果

列表裡的標題太長、儀表盤上的設備名超出寬度,這時候與其粗暴截斷,不如讓文字自己滾起來。Android 的 TextView 原生支持跑馬燈(marquee),但默認情況下很難觸發——它要求控件獲得焦點,而在非焦點模式下幾乎不會滾動。解法是繼承 TextView,強行讓 isFocused() 永遠返回 true。

自定義 MarqueTextView

package com.godinsec.seland.ui.tools;

import android.content.Context;
import android.text.TextUtils.TruncateAt;
import android.util.AttributeSet;
import android.widget.TextView;

public class MarqueTextView extends TextView {

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

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

    public MarqueTextView(Context context) {
        super(context);
        init(context);
    }

    private void init(Context context) {
        // 關鍵:把省略策略設為 marquee
        setEllipsize(TruncateAt.MARQUEE);
    }

    @Override
    public boolean isFocused() {
        // 讓系統一直認為本控件持有焦點,跑馬燈才會啟動
        return true;
    }
}

這裡重寫 isFocused() 是整個效果的支點。系統判斷是否啟動 marquee 動畫的依據之一,就是控件是否處於焦點狀態;由於普通 TextView 在列表項裡通常拿不到焦點,動畫自然不會跑。直接讓這個方法恆為真,是最省事的做法。

XML 中使用

<com.godinsec.seland.ui.tools.MarqueTextView
    android:id="@+id/tv_attention_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_vertical"
    android:layout_weight="1"
    android:ellipsize="marquee"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:marqueeRepeatLimit="marquee_forever"
    android:singleLine="true"
    android:text="XXXXXXXXXXXXXXXXXX"
    android:textColor="@color/textcolor_black_b2"
    android:textSize="@dimen/text_sp_s3" />

幾個屬性缺一不可:singleLine="true" 限定單行,ellipsize="marquee" 指定滾動策略,marqueeRepeatLimit="marquee_forever" 讓它無限循環(不設置默認只滾幾次就停),focusable 與 focusableInTouchMode 則是配合焦點判斷的補充。

兩個實戰提醒

第一,layout_width="wrap_content" 時文字會被撐開而不換行,marquee 也就無從觸發,所以父容器寬度必須受限(例如上面的 layout_weight="1" 配合 0dp 寬度),讓文字真的「放不下」。

第二,重寫 isFocused() 返回 true 有副作用:同一頁面多個此類控件並存時,焦點狀態會互相干擾,可能導致只有一個能滾。若遇到這種情況,可以改為判斷「文字寬度是否超出控件寬度」再決定返回值,精確控制哪些該滾。

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