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

Android 跑馬燈效果:讓文字在控件中滾動顯示

所謂「跑馬燈」效果,是指當文字長度超過控件能容納的空間時,文字會在控件內自動滾動。要實現它,首先在布局檔中加上這幾個屬性:

android:singleLine="true"
android:ellipsize="marquee"
android:focusableInTouchMode="true"
android:focusable="true"

需要特別注意:layout_width 必須寫成固定值,不能是 wrap_content 或 fill_parent,而且寬度要足以容納較長的文字。此外還可用 android:marqueeRepeatLimit 設定滾動次數,設為 marquee_forever 便會一直滾動。

然而這種跑馬燈只有在控件取得焦點時才會滾動。若想讓內容「無時無刻」都在滾動,就必須自訂控件,重寫三個方法:

package cn.etzmico.marqueetest;

import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.Button;

public class MarqueeButton extends Button {

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

    @Override
    protected void onFocusChanged(boolean focused, int direction,
            Rect previouslyFocusedRect) {
        if (focused)
            super.onFocusChanged(focused, direction, previouslyFocusedRect);
    }

    @Override
    public void onWindowFocusChanged(boolean hasWindowFocus) {
        if (hasWindowFocus)
            super.onWindowFocusChanged(hasWindowFocus);
    }

    @Override
    public boolean isFocused() {
        return true;
    }
}

關鍵在於把 isFocused() 永遠回傳 true,並在焦點變更時做出對應處理,藉此「欺騙」系統讓控件持續保有焦點,滾動便不會中斷。接著在布局檔中改用這個自訂控件即可:

<cn.easymobi.application.memorytest.MarqueeButton
    android:layout_width="216dip"
    android:layout_height="wrap_content"
    android:id="@+id/btSecond"
    android:background="@drawable/button_test2"
    android:layout_marginTop="15dip"
    android:text="@string/calculate"
    android:ellipsize="marquee"
    android:gravity="center"
    android:textColor="@color/white"
    android:textStyle="bold"
    android:focusable="true"
    android:marqueeRepeatLimit="marquee_forever"
    android:focusableInTouchMode="true"
    android:scrollHorizontally="true"
    android:singleLine="true"
    android:paddingLeft="50dip"
    android:paddingRight="50dip"
    android:textSize="20dip" />
Copyright © Linux教程網 All Rights Reserved