標籤:
TextView跑馬燈簡單效果
<!--簡單樣本--> <TextView android:text="@string/longWord" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textView1" android:ellipsize="marquee" android:singleLine="true" android:focusable="true" android:focusableInTouchMode="true" />
TextView跑馬燈效果的幾個常用屬性,其中ellipsize、singleLine、focusable、focusableInTouchMode 這幾個是必須的,其他可選
<!--啟用焦點--> android:focusable="true" <!--單行顯示--> android:singleLine="true" <!--這裡設定為超出文本後滾動顯示--> android:ellipsize="marquee" <!--這個是設定滾動幾次,這裡是無限迴圈--> android:marqueeRepeatLimit="marquee_forever" <!--TouchMode模式的焦點啟用--> android:focusableInTouchMode="true" <!--橫向超出後是否有橫向捲軸--> android:scrollHorizontally="true"
:
這裡是一個TextView跑馬燈效果貌似是ok的,但是頁面的布局一般都是很複雜的,有的時候一個頁面可能有多個跑馬燈效果,這裡如果我們放置兩個或者更多的TextView,那麼跑馬燈的效果怎麼樣呢?
這裡我們再來寫一個TextView 看下效果, 從中可以看出,兩個相同的TextView,發現第一個是有跑馬燈效果的,而第二個是沒有的,這是什麼情況呢?
通過萬能的百度,我們瞭解到,TextView預設是第一個擷取游標,而後面TextView是沒有擷取到游標,而跑馬燈效果是需要擷取到游標的,這裡我們知道原因了,那麼就來擴充下TextView,讓所有的
TextView 擷取到游標。
:
TextView 擴充 跑馬燈效果
1、首建立一個marqueeText的java類,並且該類繼承TextView
2、marqueeText 實現TextView的三個建構函式,並且重載isFoused()方法
/** * Created by Darren on 2015/2/23. * 設定所有的TextView都有跑馬燈效果 */public class marqueeText extends TextView { public marqueeText(Context context) { super(context); } public marqueeText(Context context, AttributeSet attrs) { super(context, attrs); } public marqueeText(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } //TextView預設設定是第一個擷取到的游標, //如果想讓所有的TextView都有跑馬燈效果,則讓所有的TextView都擷取到游標就行了 //這裡return true 就是讓所有的TextView都擷取到游標 @Override public boolean isFocused() { return true; }}View Code
3、在設計頁面中我們把TextView改成marqueeText
<TextView android:text="@string/longWord" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textView1" android:ellipsize="marquee" android:singleLine="true" android:focusable="true" android:focusableInTouchMode="true" /> <sh.geeko.marqueetext.marqueeText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/textView2" android:text="@string/longWord" android:layout_below="@id/textView1" android:layout_marginTop="20dp" android:ellipsize="marquee" android:singleLine="true" android:focusable="true" android:focusableInTouchMode="true" />
View Code
這裡我們來看下具體的實現效果:
源碼下載
Android TextView跑馬燈效果