1. 程式人生 > >Android TextView實現跑馬燈效果

Android TextView實現跑馬燈效果

在實際的開發中,我們有時候需要滾動的顯示資訊,這就是我們所說的跑馬燈效果。

Android中的TextView可以很容易的顯示這個效果,只需要新增以下屬性就可以了

android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:singleLine="true"

但是這樣子有一個缺點,就是這種狀態的跑馬燈只能在TextView處於焦點狀態的時候,它才會滾動,對於實際的開發應用中很不實用,

為了是跑馬燈無論在什麼情況下都能跑起來,這裡需要自定義一個TextView,它繼承TextView,並且重寫isFocuse()方法,讓它永遠返回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);
	}
	
	@Override
	public boolean isFocused() {
		return true;
	}

}


在xml中引用

<com.heynine.widget.view.MarqueeTextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:ellipsize="marquee"
        android:marqueeRepeatLimit="marquee_forever"
        android:singleLine="true"
        android:text="@string/marquee_text1" />

    <com.heynine.widget.view.MarqueeTextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:ellipsize="marquee"
        android:marqueeRepeatLimit="marquee_forever"
        android:singleLine="true"
        android:text="@string/marquee_text2" />

這樣就可以顯示了

效果圖如下