之前在網上找了很多關於TextView的跑馬燈效果實現的例子,實現起來都存在一些問題,例如一種是完全重畫一個跑馬燈,還有就是隻設置TextView的相關屬性使其具有跑馬燈的效果,總的來說這兩種方法都是可行的,但是都有其不足之處,第一種太複雜,實現起來比較麻煩,第二種呢,它只能在TextView獲得焦點的時候纔有跑馬燈的效果,這樣有時候並不能達到我們所要求的效果。我通過網上的一些例子自己在做了一些改動,就實現了現在不用獲取焦點也能“跑”起來的效果。
首先,寫一個類,讓其繼承自TextView:
- public class MarqueeText extends TextView {
- public MarqueeText(Context con) {
- super(con);
- }
- public MarqueeText(Context context, AttributeSet attrs) {
- super(context, attrs);
- }
- public MarqueeText(Context context, AttributeSet attrs, int defStyle) {
- super(context, attrs, defStyle);
- }
- @Override
- public boolean isFocused() {
- return true;
- }
- @Override
- protected void onFocusChanged(boolean focused, int direction,
- Rect previouslyFocusedRect) {
- }
- }
然後再將我們已經寫好的這個控件(MarqueeText)放到佈局文件中,例如main.xml:
<!-- 在佈局文件中用自己寫的控件只需要寫類的全名就行,如下com.example這是包名,後面再跟類名就行了 -->
- <com.example.MarqueeText
- android:id="@+id/AMTV1"
- android:layout_width="400dip"
- android:layout_height="wrap_content"
- android:layout_marginLeft="80dip"
- android:textSize="25sp"
- android:textColor="@android:color/black"
- android:lines="1"
- android:focusable="true"
- android:focusableInTouchMode="true"
- android:scrollHorizontally="true"
- android:marqueeRepeatLimit="marquee_forever"
- android:ellipsize="marquee"
- android:background="#2FFFFFFF"
- android:text="這纔是真正的文字跑馬燈效果,文字移動速度,文字移動方向,文字移動的樣式,動畫等等……"
- />
關於MarqueeText類中爲什麼要複寫onFocusChanged()方法,那是因爲如果不寫,在Textview 獲得焦點後,再失去焦點時字就會停止“跑”了,所以如果想讓它一直跑下去就複寫onFocusChanged(),並且裏面什麼也不做(主要是不能調用父類的方法)。