Android TextView跑馬燈效果


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

這里我們來看下具體的實現效果:

 

源碼下載

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM